Sub topic 9
Deep Copies with structuredClone
This chapter assumes you already know how spread syntax makes shallow copies and how nested immutable updates copy only the objects along a changed path. It also assumes you are comfortable with Date, Map, and Set, and with try/catch. All examples run in Node.js 17 or later and in every current browser, where structuredClone is a global function.
A shallow copy duplicates one level and shares everything below it. Sometimes you need the opposite: a full, independent copy where no nested object or array is shared with the original. That is a deep copy. structuredClone is the built-in way to make one.
What structuredClone Does
structuredClone(value) walks the whole value graph and builds new copies of every object and array it finds. It uses the structured clone algorithm, which is the same algorithm browsers use to send data to Web Workers with postMessage and to store data in IndexedDB. Because that algorithm was built to move real application data, it understands many built-in types, not only plain objects.
const original = {
user: { name: 'Ada', roles: ['admin'] },
created: new Date('2024-01-01T00:00:00Z')
};
const clone = structuredClone(original);
clone.user.roles.push('editor');
clone.user.name = 'Grace';
console.log(original.user.name); // 'Ada'
console.log(original.user.roles); // ['admin']
console.log(clone.user === original.user); // false
console.log(clone.created instanceof Date); // trueNo reference is shared between original and clone. Every nested object is new, so a change at any depth stays in the copy.
Why Not JSON.parse(JSON.stringify(...))?
Before structuredClone existed, the common trick was to serialize to JSON and parse it back. That trick gives a deep copy, but it changes your data along the way. JSON only has strings, numbers, booleans, null, arrays, and plain objects, so anything else is converted or dropped.
const original = {
created: new Date('2024-01-01T00:00:00Z'),
tags: new Set(['a', 'b']),
scores: new Map([['ada', 10]]),
missing: undefined,
ratio: NaN
};
const viaJson = JSON.parse(JSON.stringify(original));
console.log(typeof viaJson.created); // 'string'
console.log(viaJson.tags); // {}
console.log(viaJson.scores); // {}
console.log('missing' in viaJson); // false
console.log(viaJson.ratio); // null
const viaClone = structuredClone(original);
console.log(viaClone.created instanceof Date); // true
console.log(viaClone.tags.has('a')); // true
console.log(viaClone.scores.get('ada')); // 10
console.log('missing' in viaClone); // true
console.log(Number.isNaN(viaClone.ratio)); // trueThe JSON version loses data without raising an error. A Date becomes a string, so a later call to viaJson.created.getTime() throws. A Set and a Map become empty objects, and their contents are gone. These bugs tend to surface far from the line that caused them.
Supported Types
The structured clone algorithm supports these values:
| Category | Types |
|---|---|
| Primitives | string, number (including NaN and Infinity), boolean, null, undefined, BigInt |
| Containers | plain objects, arrays, Map, Set |
| Built-in objects | Date, RegExp, Boolean/Number/String wrapper objects |
| Binary data | ArrayBuffer, typed arrays such as Uint8Array, DataView |
| Errors | Error, TypeError, RangeError, and the other standard error types |
| Browser objects | Blob, File, ImageData, and some others (browser only) |
Two more behaviors make it reliable for real data graphs.
Circular References
An object that points back to itself makes JSON.stringify throw. structuredClone keeps track of what it has already copied, so it rebuilds the cycle in the copy.
const node = { name: 'root' };
node.self = node;
const copy = structuredClone(node);
console.log(copy.self === copy); // true, the cycle is rebuilt in the copy
console.log(copy === node); // false
try {
JSON.stringify(node);
} catch (err) {
console.log(err.name); // 'TypeError' (circular structure)
}Shared References Inside the Value
If two properties point to the same object, the clone's two properties also point to one shared copy. The shape of the graph is kept.
const address = { city: 'London' };
const people = { home: address, billing: address };
const cloned = structuredClone(people);
console.log(cloned.home === cloned.billing); // true, still one object
console.log(cloned.home === address); // false, but a new oneThe JSON trick would give you two separate address objects. Changing cloned.home.city would then no longer change cloned.billing.city, which is a behavior change.
What structuredClone Cannot Copy
The algorithm copies data, not behavior. Knowing the limits below prevents most surprises.
Functions and DOM Nodes Throw
Functions, including methods defined on an object, cannot be cloned. Neither can DOM nodes, WeakMap, WeakSet, or symbol values. The call throws a DataCloneError.
function tryClone(value) {
try {
return structuredClone(value);
} catch (err) {
console.log(err.name); // 'DataCloneError'
return undefined;
}
}
tryClone({ onClick() {} });
tryClone({ id: Symbol('id') });This error comes up often with objects from libraries, which may hold callbacks or internal handles. Before cloning, extract the plain data first.
Class Instances Lose Their Prototype
A class instance is cloned as a plain object. Its own data properties survive, but its prototype chain does not, so its methods are gone.
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.hypot(this.x, this.y);
}
}
const p = new Point(3, 4);
const c = structuredClone(p);
console.log(c.x); // 3
console.log(c instanceof Point); // false
console.log(typeof c.length); // 'undefined'To keep behavior, rebuild the instance from the cloned data, for example new Point(c.x, c.y). Another option is a clone() method on the class.
Property Metadata Is Not Preserved
Only own, enumerable, string-keyed properties are copied, and they become ordinary writable data properties. As a result:
- Getters are called once, and their results are stored as plain values.
- Setters are dropped.
- Non-enumerable properties and symbol-keyed properties are skipped without an error.
- Frozen and sealed status are lost.
const source = Object.freeze({
a: 1,
[Symbol('secret')]: 2,
get computed() { return this.a * 10; }
});
const out = structuredClone(source);
console.log(Object.isFrozen(out)); // false
console.log(Object.getOwnPropertySymbols(out)); // []
console.log(Object.getOwnPropertyDescriptor(out, 'computed').value); // 10Transferring Instead of Copying
structuredClone takes an optional second argument, { transfer: [...] }. Transferable objects such as ArrayBuffer are moved into the clone instead of copied. The original buffer is detached, and its length becomes 0. This avoids copying large binary data when you only need the data in one place.
const buffer = new ArrayBuffer(1024);
const moved = structuredClone({ buffer }, { transfer: [buffer] });
console.log(buffer.byteLength); // 0, the original is detached
console.log(moved.buffer.byteLength); // 1024You will mostly see this with Web Workers. It is rarely needed in ordinary state management.
Cost and When to Reach for It
A deep clone copies every node in the graph. The work and memory grow with the total size of the value, not with the size of your change. Every nested object in the result also gets a new identity, so clone.settings === original.settings is false even if you never changed settings. Code that detects changes by comparing references will see every branch as changed.
That makes structuredClone a poor fit for routine state updates, where you change one field and want everything else shared. Nested spread updates, and the structural sharing covered in the next chapter, are the better tools there. structuredClone fits these cases:
- Defensive copies at a boundary. You receive data from code you don't control and plan to mutate it locally.
- Test fixtures. Each test gets a fresh copy of a base object, so one test cannot pollute another.
- Snapshots of data that will be mutated in place later, such as a draft form you might discard.
- Passing data to workers or other contexts that use the same algorithm.
| Approach | Depth | Keeps Date/Map/Set | Handles cycles | Keeps prototypes | Shares unchanged branches |
|---|---|---|---|---|---|
| Spread / Object.assign | One level | Copies the reference | Not applicable | No (plain object result) | Yes, below the top level |
| JSON round-trip | Full | No | Throws | No | No |
| structuredClone | Full | Yes | Yes | No | No |
| Library cloneDeep (e.g. Lodash) | Full | Yes | Yes | Yes, in many cases | No |
Common Mistakes
- Using
structuredCloneon every state update. This breaks reference-equality checks and wastes memory. Copy only the changed path instead. - Cloning objects that hold callbacks, then getting a
DataCloneErrorat runtime. Clone the plain data, not the wrapper object. - Expecting
instanceofchecks or methods to work on cloned class instances. - Assuming a clone of frozen data is also frozen.
- Relying on symbol-keyed or non-enumerable properties surviving the copy.
Exercise
You clone const s = { at: new Date(0), list: [1, 2], meta: undefined } with JSON.parse(JSON.stringify(s)) and with structuredClone(s). For each result, what are typeof result.at and 'meta' in result?
Show answer
The JSON result has typeof at === 'string' and 'meta' in result === false, because the Date was converted to an ISO string and the undefined property was dropped. The structuredClone result has typeof at === 'object' (it is a real Date) and 'meta' in result === true.
Exercise
A reducer handles every action with const next = structuredClone(state); next.count += 1; return next;. The UI re-renders every list component on every action, even components whose data did not change. Why, and what should the reducer do instead?
Show answer
structuredClone gives every nested object a new identity, so reference-equality checks such as next.items === state.items are always false and every component looks changed. The reducer should copy only the changed path, for example return { ...state, count: state.count + 1 }, so unchanged branches keep their references.
Exercise
Write a function cloneUser(user) for instances of class User { constructor(name, joined) { this.name = name; this.joined = joined; } greet() { return 'Hi ' + this.name; } }. It must return a real User whose joined Date is not shared with the original.
Show answer
function cloneUser(user) { const data = structuredClone({ name: user.name, joined: user.joined }); return new User(data.name, data.joined); } Cloning the plain data copies the Date deeply, and calling the constructor restores the prototype, so greet() works and result.joined !== user.joined.