Course contentsShow
← JavaScript
Lesson 836 of 2,72319. ArraysFree lesson

Shallow vs Deep Copying with Non-Mutating Methods

Understand how non-mutating methods create shallow copies and implications for nested arrays.

Shallow vs Deep Copying with Non-Mutating Methods

You'll learn why non-mutating array methods create shallow copies and what that means for nested arrays.

The Core Idea

When you use non-mutating methods like slice(), concat(), toReversed(), toSorted(), or toSpliced(), JavaScript creates a shallow copy of your array. This means the new array is a separate container, but if the original array contains objects or nested arrays, both arrays still share references to those same nested values.

Think of it like photocopying a folder full of sticky notes pointing to other documents. You get a new folder (the array copy), but the sticky notes inside still point to the same original documents (the nested arrays or objects).

Shallow Copy in Action

const original = [1, 2, [3, 4]];
const copy = original.slice();

copy[0] = 99;           // Changes only the copy
copy[2][0] = 999;       // Changes BOTH arrays!

console.log(original);  // [1, 2, [999, 4]]
console.log(copy);      // [99, 2, [999, 4]]

The top-level elements are independent, but the nested array [3, 4] is shared between both arrays.

Why This Matters

All the non-mutating methods you've learned create shallow copies. If your array contains primitives (numbers, strings, booleans), you're safe. But with nested arrays or objects, modifications inside the nested structures will affect both the original and the copy.

What About Deep Copies?

JavaScript's built-in array methods don't provide deep copying. For truly independent nested structures, you'd need techniques beyond what we've covered so far (though we'll explore those later in your journey).

Key Takeaway: Non-mutating array methods create shallow copies—the new array is separate, but nested arrays or objects are still shared references between the original and copy.