JavaScript2 min read
structuredClone() - Native Deep Copy
Finally! A built-in way to deep clone objects. No more JSON tricks
S
Shahar Amir
The Old Way (Broken)
javascript
12345
// Shallow copy - nested objects are still referencedconst copy = { ...original };
// JSON trick - loses functions, dates, undefinedconst copy = JSON.parse(JSON.stringify(original));The New Way
javascript
123456789101112
const original = { name: 'Shahar', date: new Date(), nested: { value: 42 }, set: new Set([1, 2, 3])};
const copy = structuredClone(original);
// Modify copy - original stays unchangedcopy.nested.value = 100;console.log(original.nested.value); // Still 42!What It Handles
javascript
1234567
// ✅ Works with:structuredClone(new Date()); // DatesstructuredClone(new Map()); // MapsstructuredClone(new Set()); // SetsstructuredClone(/regex/); // RegExpstructuredClone(new ArrayBuffer()); // ArrayBufferstructuredClone({ nested: {} }); // Nested objectsWhat It Can't Clone
javascript
1234
// ❌ Throws error:structuredClone({ fn: () => {} }); // FunctionsstructuredClone(document.body); // DOM nodesstructuredClone({ sym: Symbol() }); // SymbolsReal Use Case
javascript
123456789101112
// Immutable state updatefunction updateUser(state, updates) { const newState = structuredClone(state); Object.assign(newState.user, updates); return newState;}
// Form resetconst defaultForm = { name: '', email: '', items: [] };function resetForm() { return structuredClone(defaultForm);}Browser Support
Available in all modern browsers and Node.js 17+.
No library needed. No hacks. Just structuredClone().
#objects#deep-copy#es2022#fundamentals
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.