1
var arr  = [ ['hello', 'and', 'hi'], [2,3,4] ],
    arr2 = arr.slice();
arr2[1].push(44);
arr[0] = "new value";

console.log(arr, arr2);

//["new value", [2, 3, 4, 44]]
//[["hello", "and", "hi"], [2, 3, 4, 44]]

Isn't arr2 = arr.slice() supposed to create a new copy of arr? Therefore, arr2[1].push(44) won't effect the original arr

Can anyone tell me why the console logged arr has number 44 in its second element?

hsz
  • 148,279
  • 62
  • 259
  • 315
Zoe
  • 99
  • 1
  • 3
  • 8
  • It copies the new array with the same elements. – zerkms Oct 21 '15 at 08:38
  • Because you copy only parent array, you also need copy all child arrays too, like this https://jsfiddle.net/o96hL8L9/2/ – Oleksandr T. Oct 21 '15 at 08:38
  • [Source](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice) : The slice() method returns a shallow copy of a portion of an array into a new array object. – Harsh Gupta Oct 21 '15 at 08:39

1 Answers1

1

From documentation:

For object references (and not the actual object), slice copies object references into the new array. Both the original and new array refer to the same object. If a referenced object changes, the changes are visible to both the new and original arrays.

reference

So it's a desired behaviour - you have copied a reference to the second array so it has been changed in both arr and arr2 variables.

hsz
  • 148,279
  • 62
  • 259
  • 315