Sub topic 4
Making Deep Copies with structuredClone
This chapter assumes you know how JavaScript objects, arrays and primitives behave. It also assumes you understand that spread copies only the top level, and that a JSON round-trip changes or drops some types. Both points were covered in the previous chapters. You should be able to run code in a browser console or in Node.js 17 or later.
Here you will learn what structuredClone is, how to call it, how it works at a high level, and how to confirm that a copy really is independent. Later chapters cover the full list of supported types, circular references, errors, and the values it drops.
What structuredClone is
structuredClone is a global function built into browsers, Node.js, Deno and Bun. It takes a value and returns a deep copy of it. A deep copy is a new value in which every nested object and array is also new, so changing the copy at any depth never changes the original.
The function implements the structured clone algorithm, which is defined in the HTML standard. Browsers have used this algorithm for years to pass data to Web Workers and to store data in IndexedDB. structuredClone makes the same algorithm available as a single function call.
The signature is:
structuredClone(value);
structuredClone(value, { transfer: [/* transferable objects */] });The first argument is the value to copy. The optional second argument is an options object. Its only option is transfer, which has its own chapter later. For everyday copying you pass just the value.
A first deep copy
Here is the problem from the shallow copy chapter, solved with structuredClone:
const original = { user: { name: 'Ada' }, tags: ['a'] };
const deep = structuredClone(original);
deep.user.name = 'Grace';
deep.tags.push('b');
console.log(original.user.name); // 'Ada'
console.log(original.tags); // ['a']
console.log(deep.user.name); // 'Grace'
console.log(deep.tags); // ['a', 'b']With spread, original.user and shallow.user were the same object. With structuredClone, deep.user is a new object that holds the same data. You can check this with strict equality:
const original = { user: { name: 'Ada' }, tags: ['a'] };
const deep = structuredClone(original);
console.log(deep === original); // false
console.log(deep.user === original.user); // false
console.log(deep.tags === original.tags); // false
console.log(deep.user.name === original.user.name); // true (same primitive value)Primitive values such as strings and numbers have no identity to share, so the copy holds equal values. Every object in the structure has a new identity.
Where it beats the JSON round-trip
The JSON round-trip was the usual deep copy trick before structuredClone. It works only for data that JSON can represent. structuredClone copies many built-in types without converting them:
const original = {
when: new Date(0),
ids: new Set([1, 2]),
meta: new Map([['k', { v: 1 }]])
};
const copy = structuredClone(original);
console.log(copy.when instanceof Date); // true
console.log(copy.ids.has(2)); // true
console.log(copy.meta.get('k') === original.meta.get('k')); // false
copy.meta.get('k').v = 99;
console.log(original.meta.get('k').v); // 1The Date is still a Date, so copy.when.getTime() works. The Set and Map are real collections, and the object stored inside the Map was copied as well. Values like undefined, NaN, Infinity and -0 also come through unchanged, where JSON turned them into null or dropped them.
| Technique | New top-level object | New nested objects | Keeps Date, Map, Set | Handles cycles |
|---|---|---|---|---|
| `const b = a` | No | No | Yes (same object) | Yes (same object) |
| `{ ...a }` or `Object.assign({}, a)` | Yes | No | Nested ones shared | Shared, not copied |
| `JSON.parse(JSON.stringify(a))` | Yes | Yes | No | Throws `TypeError` |
| `structuredClone(a)` | Yes | Yes | Yes | Yes |
How it works: serialize, then rebuild
You can think of structuredClone as two steps. The specification calls them StructuredSerialize and StructuredDeserialize.
- Serialize. The algorithm walks the value and records each part in an internal, engine-specific form. Primitives are recorded as they are. For each object, it records the object's kind (plain object, array,
Date,Mapand so on) and its contents. It keeps a memory of objects it has already visited, so an object that appears twice is recorded once. - Deserialize. The algorithm reads that record and builds brand-new objects of the recorded kinds, filling in their contents.
The original is only read, never changed. The result shares no objects with the original because every object in it was built from the record.
This model explains several behaviours you will meet later:
- Only data gets recorded. Behaviour such as functions and class methods has no place in the record, which is why functions cause an error and class instances come back as plain objects.
- For plain objects, only own enumerable string-keyed properties are recorded. That is why symbol keys and non-enumerable properties are dropped.
- Visited objects are remembered, which is why circular and shared references survive.
Calling it with different inputs
structuredClone accepts more than objects. Any supported value can be the top-level argument:
console.log(structuredClone(42)); // 42
console.log(structuredClone('text')); // 'text'
console.log(structuredClone(undefined)); // undefined
console.log(structuredClone(null)); // null
const d = new Date(0);
const dCopy = structuredClone(d);
console.log(dCopy === d, dCopy.getTime()); // false 0
const nested = [[1, 2], [3, [4, 5]]];
const nestedCopy = structuredClone(nested);
nestedCopy[1][1].push(6);
console.log(nested[1][1]); // [4, 5]Arrays at any depth are copied, and the result is a real array, so Array.isArray(nestedCopy) is true.
The call is synchronous. It returns the copy directly, not a promise, so there is nothing to await.
Practical patterns
Fresh copies of defaults
A common bug is handing out a shared defaults object that callers then mutate. Cloning the defaults for each caller fixes it:
const defaults = { theme: { mode: 'light', accent: '#06c' }, recent: [] };
function createSettings() {
return structuredClone(defaults);
}
const a = createSettings();
const b = createSettings();
a.theme.mode = 'dark';
a.recent.push('report.pdf');
console.log(b.theme.mode); // 'light'
console.log(defaults.recent.length); // 0With { ...defaults }, the push into a.recent would have changed defaults.recent and therefore every later settings object.
Snapshots for undo history
When you keep a history of states, each entry must be frozen in time. A snapshot that shares nested objects with the live state changes whenever the live state changes.
const history = [];
const state = { items: [{ id: 1, done: false }], updatedAt: new Date(0) };
function snapshot(s) {
history.push(structuredClone(s));
}
snapshot(state);
state.items[0].done = true;
state.updatedAt = new Date();
console.log(history[0].items[0].done); // false
console.log(history[0].updatedAt.getTime()); // 0Protecting input you do not own
A function that receives an object and needs to modify it can clone it first, so the caller's data stays untouched:
function normalizeOrder(order) {
const result = structuredClone(order);
result.lines.forEach((line) => {
line.sku = line.sku.toUpperCase();
});
return result;
}
const input = { lines: [{ sku: 'ab-1', qty: 2 }] };
const output = normalizeOrder(input);
console.log(input.lines[0].sku); // 'ab-1'
console.log(output.lines[0].sku); // 'AB-1'Verifying that a copy is independent
Equal content and independence are two separate properties, and you can test each one.
To check equal content in Node.js, isDeepStrictEqual from node:util compares values deeply, including Date, Map and Set contents:
const { isDeepStrictEqual } = require('node:util');
const original = { when: new Date(0), ids: new Set([1, 2]), list: [{ n: 1 }] };
const copy = structuredClone(original);
console.log(isDeepStrictEqual(copy, original)); // trueTo check independence, look for any object that appears in both structures. This helper walks plain objects and arrays and reports the paths where the two values hold the very same object. It does not look inside Map or Set.
function findSharedObjects(a, b, path = '$', seen = new Set()) {
const shared = [];
if (a === null || typeof a !== 'object') return shared;
if (seen.has(a)) return shared;
seen.add(a);
if (a === b) {
shared.push(path);
return shared;
}
if (b === null || typeof b !== 'object') return shared;
for (const key of Object.keys(a)) {
shared.push(...findSharedObjects(a[key], b[key], `${path}.${key}`, seen));
}
return shared;
}
const original = { user: { name: 'Ada' }, tags: ['a'] };
console.log(findSharedObjects({ ...original }, original));
// [ '$.user', '$.tags' ]
console.log(findSharedObjects(structuredClone(original), original));
// []The spread copy reports two shared paths. The structuredClone copy reports none.
Common errors
Calling it as a method
structuredClone is a global function, not a method on Object or on the value. Object.structuredClone(x) and x.structuredClone() fail with a TypeError because those properties do not exist. Call structuredClone(x).
Calling it with no argument
structuredClone() with no argument throws a TypeError, because the value argument is required. Passing undefined explicitly is allowed and returns undefined.
Expecting it to copy behaviour
structuredClone copies data. If your object holds a function, the call throws a DataCloneError. If it is a class instance, the copy loses its prototype and methods. Both cases have their own chapters. For now, remember that a copy of a plain-data structure is safe, and anything with behaviour needs a closer look.
Wrapping it in a check that never fails
structuredClone can throw, so code that copies data it does not control should be prepared for that:
function safeClone(value) {
try {
return { ok: true, value: structuredClone(value) };
} catch (err) {
return { ok: false, error: err.name };
}
}
console.log(safeClone({ a: 1 }).ok); // true
console.log(safeClone({ f() {} }).error); // 'DataCloneError'Cloning when you do not need to
A deep copy visits every nested value, so its cost grows with the size of the data. Cloning a large state tree on every keystroke or inside a tight loop can be slow. If you only replace top-level fields, a shallow copy is cheaper and correct. If you only read the data, you do not need a copy at all. The last chapter of this tutorial covers how to choose.
Exercises
Exercise
Given const config = { db: { host: 'localhost', ports: [5432] } }; const c = structuredClone(config); c.db.ports.push(5433); what do config.db.ports and c.db === config.db evaluate to?
Show answer
config.db.ports is still [5432], and c.db === config.db is false. structuredClone builds a new object for db and a new array for ports, so pushing into the copy's array does not affect the original.
Exercise
A teammate writes const snapshot = { ...state, updatedAt: new Date(state.updatedAt) }; to store undo history, where state contains an items array of objects. Explain the bug and fix it.
Show answer
Spread copies only the top level, so snapshot.items is the same array as state.items. Later changes to items or their objects also change the snapshot. Use const snapshot = structuredClone(state); which copies items, every object inside it, and the Date as a real Date.
Exercise
Using the serialize-then-rebuild model, explain why structuredClone can copy a Map but throws on an object that contains a method.
Show answer
During serialization, a Map is recorded as its kind plus its key-value entries, all of which are data that can be rebuilt as a new Map. A function has no data representation the algorithm can record and rebuild, so serialization fails and the call throws a DataCloneError.