Deep Clone with structuredClone
What you'll learn: How to use JavaScript's native structuredClone() function to create true deep copies of complex objects without external libraries.
The Modern Solution to Deep Cloning
Remember the deep clone problem? JSON stringify/parse fails with functions, dates, and circular references. structuredClone() is the modern, built-in answer. It creates a complete, independent copy of an object—including nested objects, arrays, dates, maps, sets, and even handles circular references automatically.
Think of it like a high-tech photocopier that not only copies the pages but also reproduces any photos, diagrams, or sticky notes attached—preserving everything exactly as it was, but completely separate from the original.
Basic Usage
const original = {
name: 'Alice',
details: {
age: 30,
registered: new Date('2024-01-01')
},
hobbies: ['reading', 'coding']
};
const clone = structuredClone(original);
clone.details.age = 31;
clone.hobbies.push('gaming');
console.log(original.details.age); // 30 (unchanged!)
console.log(original.hobbies.length); // 2 (unchanged!)
console.log(clone.details.registered instanceof Date); // true (preserved!)
What It Handles Well
structuredClone() supports:
- Nested objects and arrays
- Dates, RegExps, Maps, Sets
- Typed arrays and ArrayBuffers
- Circular references (objects referencing themselves)
Limitations
It cannot clone:
- Functions (they'll be omitted)
- DOM nodes
- Symbols as properties
- Object prototypes (clones become plain objects)
Key Takeaway: structuredClone() is the modern, robust way to deep clone complex objects with nested structures, automatically handling most data types and circular references without needing JSON tricks.