Course contentsShow
← JavaScript
Lesson 1757 of 2,72337. Functional Programming PatternsFree lesson

Deep Cloning with structuredClone

Use structuredClone to create deep copies of nested structures safely and efficiently.

Deep Cloning with structuredClone

You'll learn how to create true deep copies of complex nested objects using JavaScript's built-in structuredClone method.

The Shallow Copy Problem Revisited

Remember how spread and Object.assign only create shallow copies? When you have nested objects or arrays, those inner structures are still shared references—not truly independent copies. This is where structuredClone shines.

What is structuredClone?

structuredClone is a global function that creates a deep clone of any value. It recursively copies all nested objects and arrays, producing a completely independent duplicate with zero shared references.

Think of it like a photocopier that doesn't just copy the cover of a book, but reproduces every page inside, every diagram, every footnote—creating an entirely separate book.

Basic Usage

const original = {
  name: 'Alice',
  address: {
    city: 'Boston',
    coords: { lat: 42.36, lng: -71.06 }
  },
  hobbies: ['reading', 'coding']
};

const clone = structuredClone(original);

// Modify nested properties
clone.address.city = 'New York';
clone.address.coords.lat = 40.71;
clone.hobbies.push('gaming');

console.log(original.address.city); // 'Boston' (unchanged!)
console.log(original.hobbies);      // ['reading', 'coding'] (unchanged!)

Unlike spread, which would have mutated the original's nested structures, structuredClone gives you true isolation.

What It Can Clone

structuredClone handles most built-in types: objects, arrays, dates, sets, maps, typed arrays, and more. It even preserves circular references!

What It Cannot Clone

Functions, DOM nodes, and certain special objects cannot be cloned—structuredClone will throw an error if you try.

Key Takeaway: Use structuredClone for true deep copies of nested structures without shared references—it's the safest, most complete cloning solution in modern JavaScript.