The JavaScript variables are not easy as it seems to be.
In this shout I am trying to demystify few of them. Feel free to add if you have experienced similar behaviors which are hidden and not written explicitly.
In this shout I am trying to demystify few of them. Feel free to add if you have experienced similar behaviors which are hidden and not written explicitly.
- Reference or Value : Always wondered are JavaScript variables are references or values. let us go through some examples.
- Scalar variables - Consider the snippet
var s1 = "I am Einstein";
var s2 = s1;
console.log("1 :: S1=" + s1);
console.log("1 :: S2=" + s2);
s1 = "I am Newton";
console.log("2 :: S1=" + s1);
console.log("2 :: S2=" + s2);
... what do you think the output can be. Here it is.
1 :: S1=I am Einstein
1 :: S2=I am Einstein
2 :: S1=I am Newton
2 :: S2=I am Einstein
- Array Types - consider the snippet
var v1 = { "name" : "Tom", "skill" : "java"};
var v2 = v1;
console.log("1 :: v1=" + JSON.stringify(v1));
console.log("1 :: v2=" + JSON.stringify(v2));
v2.skill = "java, javascript";
console.log("2 :: v1=" + JSON.stringify(v1));
console.log("2 :: v2=" + JSON.stringify(v2));
... now do you think the output would change like previous one. Here it is.
1 :: v1={"name":"Tom","skill":"java"}
1 :: v2={"name":"Tom","skill":"java"}
2 :: v1={"name":"Tom","skill":"java, javascript"}
2 :: v2={"name":"Tom","skill":"java, javascript"}
... this is because JavaScript always keep the Object/JSON as refrences. And the statement "v2=v1" copy the references not the value unlike the previous case. After the any change in v1 would also change the v2 as they are pointing to the same object.
- Vector Types (Object/JSON) - consider the snippet
var a1 = ["Einstein","Newton"];
var a2 = a1;
console.log("1 :: a1=" + a1);
console.log("1 :: a2=" + a2);
... here also the result is same as previous
console.log("2 :: a1=" + a1); console.log("2 :: a2=" + a2);
- Associative Array: Javascript Associative arrays do not keep the ordering of the same. it depends on the hashing of the keys.
var scientists = { 2: "Einstein" , "1" : "Newton" , 3: "Feynman"};
console.log("1 :: scientists=" + JSON.stringify(scientists));
var scientistsSorted = {"S2":"Einstein" , "S1" : "Newton","S3": "Feynman"};
console.log("2 :: scientists=" + JSON.stringify(scientistsSorted));
... see the output minutely,
1 :: scientists={"1":"Newton","2":"Einstein","3":"Feynman"}
2 :: scientists={"S2":"Einstein","S1":"Newton","S3":"Feynman"}
... what is going on, in case of #1, the hashing is done in an numeric way. So please be careful if you have an associative array with the keys as integer (even in form of a string), JavaScript will not be able to keep the ordering as you added. In order to avoid that you have prefix the keys with some character. see #2.
No comments:
Post a Comment