I was playing with chrome console and noticed something which I couldn't understand. I know in JS variables are copied by value and objects are copied by reference. Below code works fine as expected which outputs 2 and proves JS objects work as reference:
var objA = {a: 1};
var objB = objA;
objA.a = 2;
objB.a; // 2
However this code doesn't work as it should. I expected objB.a to output 2
but it gives 1
instead. Why?
var objA = {a: 1};
var objB = objA;
objA = {a: 2}; //Assigned whole object here instead property.
objB.a; //1 - Shouldn't this be 2 ??
I'd rather think of variables with objects as pointers to objects (like C pointers) rather than references.
In your third line, you just replaced objA
, making it "point to" another object. It does not change whatever objB
is "pointing".
By line 3, objA
now points to {a:2}
while objB
still points to whatever objA
was pointing at the time you assigned it to objB
, at line 2, which is {a:1}
.
line 1: objA -> {a:1}
line 2: objA -> {a:1} <- objB
line 3: objA -> {a:2}, objB -> {a:1}