ShaharAmir
← Back to Blog
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 referenced
const copy = { ...original };
// JSON trick - loses functions, dates, undefined
const 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 unchanged
copy.nested.value = 100;
console.log(original.nested.value); // Still 42!

What It Handles

javascript
1234567
// ✅ Works with:
structuredClone(new Date()); // Dates
structuredClone(new Map()); // Maps
structuredClone(new Set()); // Sets
structuredClone(/regex/); // RegExp
structuredClone(new ArrayBuffer()); // ArrayBuffer
structuredClone({ nested: {} }); // Nested objects

What It Can't Clone

javascript
1234
// ❌ Throws error:
structuredClone({ fn: () => {} }); // Functions
structuredClone(document.body); // DOM nodes
structuredClone({ sym: Symbol() }); // Symbols

Real Use Case

javascript
123456789101112
// Immutable state update
function updateUser(state, updates) {
const newState = structuredClone(state);
Object.assign(newState.user, updates);
return newState;
}
// Form reset
const 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.