You are pointing y
to the reference of x
which itself is pointing to the object {a:1,b:2}
.
So in memory it is:
x --> {a:1,b:2}
After you do y = x
, it becomes:
y --> x --> {a:1,b:2}
Or to put it simply:
x --> {a:20,b:2}
^
|
y -------
Now when you do y.a = 20
, since y
and x
are both pointing to the same object when properties of the object is changed through either of the references x
or y
the change will be reflected in both the references:
y --> {a:20,b:2}
^
|
x -------
That is why you get 20,2
when you get x.a
.
solved Why javascript object value is changed? [duplicate]