Sub topic 9
Deep Copies with structuredClone
This chapter assumes you already know how spread syntax makes shallow copies and why nested objects stay shared after a shallow copy. You should also be comfortable reading Node.js or browser console output. Every example runs in Node.js 17 or later and in all current browsers, where structuredClone is a global function.
What structuredClone does
A shallow copy duplicates only the top level. A deep copy duplicates every nested object and array, so the copy shares nothing with the original. structuredClone(value) returns that kind of fully independent copy. It uses the structured clone algorithm, the same algorithm browsers use to pass data to Web Workers with postMessage.
const original = { created: new Date(0), items: [{ id: 1 }] };
const clone = structuredClone(original);
clone.items[0].id = 99;
console.log(original.items[0].id); // 1
console.log(clone.created instanceof Date); // true
// structuredClone({ fn() {} }); // throws DataCloneError: functions cannot be clonedChanging clone.items[0] has no effect on original, because the copy has its own array and its own inner object. The Date also comes back as a real Date, not as a string.
Why not JSON.parse(JSON.stringify(...))?
Before structuredClone existed, the usual way to deep copy was a round trip through JSON. That trick still works for plain data, but it silently corrupts anything that JSON cannot represent.
const data = { when: new Date(0), missing: undefined, tags: new Set(['a']) };
const viaJson = JSON.parse(JSON.stringify(data));
console.log(typeof viaJson.when); // 'string'
console.log('missing' in viaJson); // false
console.log(viaJson.tags); // {}
const viaClone = structuredClone(data);
console.log(viaClone.when instanceof Date); // true
console.log('missing' in viaClone); // true
console.log(viaClone.tags.has('a')); // truestructuredClone also handles circular references. JSON.stringify throws a TypeError when it meets one.
const node = { name: 'root' };
node.self = node;
const copy = structuredClone(node);
console.log(copy.self === copy); // true, the cycle is rebuilt inside the copy
console.log(copy === node); // falseWhat it cannot clone
The algorithm copies data, not behavior. These limits are the most common source of surprises:
| Input | Result |
|---|---|
| Functions, including methods | Throws `DataCloneError` |
| DOM nodes | Throws `DataCloneError` |
| Class instances | Become plain objects, and the prototype is lost |
| Getters and setters | The current value is copied, not the accessor |
| Symbol-keyed properties | Dropped |
| `Map`, `Set`, `Date`, `RegExp`, typed arrays | Preserved |
The lost prototype catches people most often:
class Point {
constructor(x) { this.x = x; }
get double() { return this.x * 2; }
}
const p = structuredClone(new Point(2));
console.log(p.x); // 2
console.log(p instanceof Point); // false
console.log(p.double); // undefined, the getter lived on the prototypeWhen a deep copy is the right tool
A deep copy costs time and memory in proportion to the size of the whole value, even when you only plan to change one field. That makes it a poor fit for routine state updates. It works well in a few specific cases:
- Taking a snapshot for undo history or debugging, where later changes must never leak back into the snapshot.
- Making a defensive copy of input from code you do not control before you mutate it locally.
- Building test fixtures, so that each test starts from fresh, unshared data.
For ordinary updates, copying only the path that changed is cheaper, and it keeps unchanged branches identical by reference. The next chapter covers this technique.
Exercise
You run const b = structuredClone(a) where a = { at: new Date(0), list: new Map([[1, 'x']]), log() {} }. What happens, and how would you fix it if you only need the data?
Show answer
The call throws a DataCloneError because a.log is a function. To copy only the data, leave the function out first: const { log, ...data } = a; const b = structuredClone(data);. The copy then has a real Date and a real Map that are independent of the originals.
Exercise
Why is structuredClone(state) a poor choice for toggling one todo's done flag in a large state object?
Show answer
It copies the entire state, which wastes time and memory. It also gives every nested object a new reference, so reference-equality checks report that everything changed, even the parts that did not.