When arrays are assigned to another variable, the reference is passed as opposed to values. This is confirmed when you compare two arrays using ==
operator and it returns true
var a = [[1,2],[3,4],[5,6]];
var b = a; // b = [[1,2],[3,4],[5,6]]
var c = [].concat(a); // c = [[1,2],[3,4],[5,6]]
a == b; //true
a == c; //false
With the above inputs, when I modify the array b
, it mutates array a
, but not c
.
b.push([7,8]); // b = [[1,2],[3,4],[5,6], [7,8]]
a; //a = [[1,2],[3,4],[5,6], [7,8]]
c; //c = [[1,2],[3,4],[5,6]]
But when I do the below, it mutates c
.
b[0].push(5); // b = [[1,2,5],[3,4],[5,6], [7,8]]
a; //a = [[1,2,5],[3,4],[5,6], [7,8]]
c; //c = [[1,2,5],[3,4],[5,6]]
Why does this happen? This behavior happens with the usage of array methods that mutates the array.