It's important to remember
When you assign primitive values like this:
var a = b = 2;
It is the same as:
var b = 2;
var a = b;
Both a
and b
will have the value of 2.
However, if you assign objects instead of primitive values:
var a = b = [1,2,3,4];
This means:
var b = [1,2,3,4];
var a = b;
This indicates that both a
and b
are referencing the same object.
Therefore, any changes made to b
will also affect a
, and vice versa:
a.push(5);
// a <--- [1,2,3,4,5]
// b <--- [1,2,3,4,5] !! Be cautious! Changes made to b affect a too
Remember: Using a shorthand a = b = c = value
assigns the same value to all variables. But when dealing with object assignment, they share the same reference pointing to a value. Always keep this in mind.
So for object assignment, this statement:
var a = b = [1,2,3,4]; // changing a WILL impact b
does not create the same effect as
var a = [1,2,3,4]; var b = [1,2,3,4]; // altering a won't affect b