Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does changing one array alters the other?

Consider this tiny bit of javascript code:

var a = [1, 2, 3],
    b = a;

b[1] = 3;

a; // a === [1, 3, 3] wtf!?

Why does "a" change when I update "b[1]"? I've tested it in Firefox and Chrome. This doesn't happen to a simple number for example. Is this the expected behaviour?

var a = 1,
    b = a;

b = 3;

a; // a === 1 phew!
like image 492
Daniel Johansson Avatar asked Nov 27 '22 10:11

Daniel Johansson


2 Answers

It's the same array (since it's an object, it's the same reference), you need to create a copy to manipulate them separately using .slice() (which creates a new array with the elements at the first level copied over), like this:

var a = [1, 2, 3],
    b = a.slice();

b[1] = 3;

a; // a === [1, 2, 3]
like image 52
Nick Craver Avatar answered Dec 09 '22 18:12

Nick Craver


Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.

When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.

You can see the same "they're pointing to the same object" behavior with Date instances:

var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day
like image 41
Pointy Avatar answered Dec 09 '22 18:12

Pointy