Search code examples
javascriptarraysdeep-copy

In JS, why does the slice() documentation say it is a shallow copy when it looks like a deep copy?


According to the docs for Array.prototype.slice() in JavaScript, the slice() method returns a shallow copy of a portion of an array into a new array. It is my understanding that a shallow copy will only copy top level elements in an array and will not copy nested elements. However, when I run a test in my browser console, it sure looks like the slice() method is actually copying the nested elements (deep copying).

enter image description here

Where am I misunderstanding the concept of a deep copy? Please help me clarify as it relates to my exact example.

var array = [1,2,[3,4,[5,6]]];
var array2 = array.slice();

Solution

  • In this case the shallow copy means that the nested objects will be pointing to the original values. So by modifying nested objects in the sliced array, you will mutate the original.

    It's better to see on the example:

    var originalArray = [1, [2, 3], 4];
    var slicedArray = originalArray.slice();
    var nestedArray = slicedArray[1]; // [2, 3]
    nestedArray.push("oh no, I mutated the original array!");
    console.log(originalArray); // [1, [2, 3, "oh no, I mutated the original array!"], 4]