5

IIUC Array.slice(0) returns a copy of the array. Is it a shallow copy? In other words the array items still have the same memory location, but the array container gets assigned a new one?

Effectively:

let oldArray = ['old', 'array'];
let newArray = oldarray.slice(0);
let same = oldArray[0] === newArray[0]; //true 
let same = oldArray === newArray; //false
Pengyy
  • 37,383
  • 15
  • 83
  • 73
Ole
  • 41,793
  • 59
  • 191
  • 359
  • 2
    Yes, if the items in the array are objects, they will not be coped, only referenced in a new array container. You have to go to *some significant effort* to actually deep copy arrays and objects in general (thankfully). – CertainPerformance Apr 18 '18 at 02:10

2 Answers2

5

Yes,see demo:

var o = [{
  x: 1
}]
var o2 = o.slice(0)
o2[0].x = 2
console.log(o[0].x)
xianshenglu
  • 4,943
  • 3
  • 17
  • 34
3

You are correct - it does create a shallow copy.

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 selected from begin to end (end not included). The original array will not be modified.

If you are wanting a deep copy you can do the ye ole dirty dirt:

var arr = [1]; 
var arr2 = JSON.parse(JSON.stringify(arr));

arr[0] = 99;
arr2[0] = 1000;

console.log({arr, arr2});
Zze
  • 18,229
  • 13
  • 85
  • 118