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.

+3


source to share


5 answers


First, you set foo

to one object:

var foo = {a : 1};

      

and then overwrite it with a completely new object:



foo = {a : 10};

      

In this case, foo

and are bar

no longer connected, since the link is now broken.

+1


source


When you reach this line of code:

foo = {a : 10};

      



foo is assigned the variable new ; from now on there are two different variables on foo and bar, and for this reason the last line prints 2 as the bar still points to the old value.

0


source


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.

0


source


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

      

0


source


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

      

0


source







All Articles