Variables passed by reference or value (clarification)
This is my example code:
var foo = {a : 1};
var bar = foo;
console.log(bar.a);//1, as expected
foo.a = 2;
console.log(bar.a);//2, as expected, as objects are passed by reference
foo = {a : 10};
console.log(bar.a);//2, not expected, I expected 10
The last log does not give the expected result. Thinking what is the foo = {a : value}
same foo.a = value
, I expected the last result to be 10. What is wrong with my expectation? I think I am missing a big tutorial here.
source to share
You are reassigning foo
to a new object literal on the second line.
Bar
is still pointing to the old object, so you get 2 (which you changed on the 4th line).
If this explanation doesn't clear things up, it might be helpful to step back and try to understand variables, objects, and references at a higher level. Eloquent JavaScript The Data Structures chapter might be a good place to start.
edit: Point to be clarified: it's important to understand that you are not ignoring anything, you just changed the link foo
. Now they point to different things in memory. That's why Bar
it's the same.
source to share
var foo = {a : 1}; //foo refering to object {a : 1}
var bar = foo; //bar refering to same object as foo
console.log(bar.a); //1, as expected
foo.a = 2; //The object to which bar and foo are pointing gets changed
console.log(bar.a); //2, as expected, as objects are passed by reference
foo = {a : 10}; //foo starts pointing to the newly created object, whereas bar is still refering the old object(no change in bar) and the earlier object `{a : 1}` exists and poinyted to by bar
console.log(bar.a); //2, not expected, I expected 10 //hence this result
source to share
first you assigned foo to the bar at which time ref foo is sent to bar.
now if you change the value of bar.a then foo will be changed
foo = {
a: 2
}
bar = foo
console.log(bar.a) //gives 2
bar.a = 30
console.log(foo.a) //gives 30
but when you rewrite foo the connection will be lost and both will act as two separate variables
so now
foo.a = 20
console.log(bar.a) //gives 30
console.log(foo.a) //gives 20
source to share