Course contentsShow
← JavaScript
Lesson 913 of 2,72320. Array Iteration and TransformationFree lesson

Deep Cloning Nested Arrays

Understand shallow vs deep copies and techniques like structuredClone for nested immutability.

Deep Cloning Nested Arrays

What you'll learn: How to create true, independent copies of arrays containing other arrays or objects so changes don't affect the original.

The Problem with Shallow Copies

You've learned immutable techniques like using spread ([...arr]) or .slice(), but these only create shallow copies. Think of a shallow copy like photocopying a folder—you get a new folder, but the papers inside are still the same originals. If an array contains nested arrays or objects, copying the outer array doesn't copy the inner ones.

const original = [[1, 2], [3, 4]];
const shallowCopy = [...original];

shallowCopy[0][0] = 99;
console.log(original[0][0]); // 99 — Oops! Original changed too

The outer array is new, but the inner arrays are shared references.

Deep Cloning: True Independence

A deep clone copies everything recursively—like photocopying the folder and all the papers inside. Now the copy is completely independent.

Using structuredClone()

Modern JavaScript provides structuredClone() for deep cloning:

const original = [[1, 2], [3, 4]];
const deepCopy = structuredClone(original);

deepCopy[0][0] = 99;
console.log(original[0][0]); // 1 — Original unchanged!

structuredClone() works with nested arrays, objects, dates, and more. It's the safest, most reliable method for deep cloning in modern environments.

Alternative: JSON Methods (with caveats)

For simple nested structures, you can use JSON.parse(JSON.stringify(array)), but this fails with functions, undefined values, or special objects.

When Deep Cloning Matters

Use deep cloning when your arrays contain other arrays or objects and you need true immutability—especially in state management or when passing data that shouldn't be modified.

Key Takeaway: Shallow copies share nested references; deep cloning with structuredClone() creates fully independent copies of nested structures, ensuring true immutability.