Objects in javascript (like arrays) are passed around as references. So, when you do:
a.push(b)
You are pushing a reference to b
into the array a
. If you later change b
, there is only one b
so it will change in all places that refer to it, including in the array.
Another way to say this is that a.push(b)
does not make a copy of b
. What was pushed into the array just points to the same b
you've always had so if you change b
, the reference in the array just points to the one b
there is so looking at the value through the array will see the change too.
If you truly want a copy (that won't be affected by changes to the original) pushed into the array, you can make an explicit copy using .slice()
.
var a = [1,2,3];
var b = [5,4];
var c = 6;
a.push(b.slice()); // push a shallow copy of b
This is a fairly fundamental thing to grasp when learning javascript. When you pass or assign objects in javascript (and an array is one type of object), a copy is not made. Instead, you end up with more than one part of your code all pointing to the exact same object. This is obviously a feature that can be taken advantage of, but it means that when you want an independent copy that has no connection to the original, you have to explicitly make a copy.
To contrast with this, primitives such as Boolean or Number are assigned or passed as a copy.