In javascript Arrays & Objects
are passed by reference, so changing them one place affects others.
And primitives like number
, string
are passed by value, so changing them at one place doesn't affect on others.
Primitives
var a,b;
a=10;
b=a;
So b
& a
has something like bellow structure
a ---1000----> [10] a is pointing to some location(lets 1000) which have value 10
b ---1004----> [10] b is pointing to some location(lets 1004) which have value 10
Lets we increment a
by 1
now the value will be changed at the place 1000
.
a ---1000----> [11]
b ---1004----> [10]
And in Arrays and Objects
obj1 = {}; // obj1 has a reference
obj1
has an structure like bellow
------->1000--------->[{}]
obj1 -------1004----->[1000] //this '1000' is a reference which has a `{}` at it's place
This line
obj2 = obj1;
after this line obj2
& obj
share same reference
------->1000--------->[{}]
obj1 -------1004----->[1000]
obj2 -------1008----->[1000]
obj1.ab = 5;
this line is adding a field called ab
to the reference of obj1
------->1000--------->[{ab:5}]
obj1 -------1004----->[1000]
obj2 -------1008----->[1000]
And because obj1
& obj2
have same reference, you are getting the field ab
for both.
obj1 // Object {ab: 5}
obj2 // Object {ab: 5}
Note:- Any improvement in answer is appreciated.