-1

so i have this weird problem in JavaScript 'copying' an array:

var a = [0];
var b = a;
b[0]++;
alert(a);
alert(b);

gives me as alerts 1 and 1 while I was expecting 0 and 1.

If I use slice to copy the array it works fine:

var a = [0];
var b = a.slice(0);
b[0]++;
alert(a);
alert(b);

Why is this so?

I couldn't find anything at all to explain this problem to me.

Jeremy J Starcher
  • 23,369
  • 6
  • 54
  • 74
Simon
  • 397
  • 1
  • 3
  • 24
  • What's not to get? You told it that `a` and `b` are the same thing. Two "pointers" to the same thing. Whereas in the second case you create a new thing by copying the original thing, so you have two pointers to two different things. – Niet the Dark Absol May 04 '16 at 14:19
  • 1
    In the first case, you assigned the reference of a variable to second one so the value is incremented in both. In the second one, slice created a shallow copy of the first array so you were not incrementing the same value. – gurvinder372 May 04 '16 at 14:19
  • 1
    In ES6 use let b = [...a] – Niels Steenbeek May 04 '16 at 14:23

3 Answers3

2

Arrays held in variables are references to the array in memory. Unlike simple values (such as numbers or strings), statements like arr2 = arr1 simply copy the reference for the version in memory, rather than the "value" of the array.

slice() actually creates a new array from part (or in this case all) of the array it is called on, which is why your second example works differently.

In general, if you want a new copy of an array on which to perform some manipulation you should call slice() to copy it first.

SimonR
  • 1,248
  • 9
  • 10
0

When you tell a variable to be assigned to another variable, you are doing something called pass by reference, where they are both accessing the same object in memory. In this case, changing one variable will affect the other, as they both access the same object.

When you slice and assign that, you are passing by value, which means it will store the value of it instead. In this case, changing one will be isolated, as they are storing separate objects in memory.

Read here for more: What's the difference between passing by reference vs. passing by value?

Community
  • 1
  • 1
Hopeful Llama
  • 728
  • 5
  • 26
0

You aren't really copying the array when you assign a to b you're just referencing a thus when you change something on b you are actually changing it on the source a, what slice does is that it copies each item in an array to a new instance.

Sam Pettersson
  • 3,049
  • 6
  • 23
  • 37