Sub topic 4
Making Deep Copies with structuredClone
This chapter assumes you know how object references work, how spread makes a shallow copy, and why a JSON round-trip loses types. Earlier chapters covered all three. You should also be able to run code in a browser console or Node.js 17 or later.
What structuredClone does
structuredClone is a global function built into modern 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, array, Map and Set is also new, so the copy shares no mutable data with the original.
The signature is short:
const copy = structuredClone(value);
const copyWithOptions = structuredClone(value, { transfer: [] });The first argument is the value to copy. The optional second argument is an options object whose only key, transfer, has its own chapter later. Most calls pass just the value.
The function uses the structured clone algorithm, which is the same set of rules the platform uses to pass data between windows and workers. You get that algorithm without writing any messaging code.
A first deep copy
Here is the shallow-copy problem from earlier, fixed 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 === original.user); // falseSpread copied only the top level. structuredClone walks the whole structure and makes a fresh object at every level, so a change to deep cannot reach original.
Keeping built-in types
The JSON round-trip turned a Date into a string and a Set into {}. structuredClone keeps these types and also copies what they contain:
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 object stored inside the Map is cloned too. Values such as undefined, NaN and -0 also come through unchanged, where JSON would drop them or rewrite them.
The working model
To predict what structuredClone will do, keep four rules in mind:
| Input | Result |
|---|---|
| Primitive (number, string, boolean, `null`, `undefined`, bigint) | The same primitive value |
| Plain object or array | A new object or array with cloned contents |
| Supported built-in (`Date`, `Map`, `Set`, `RegExp`, typed arrays, and others) | A new instance of the same type with cloned contents |
| Unsupported value (function, DOM node, symbol) | A thrown `DataCloneError` |
Later chapters give the full list of supported types, explain how circular references are handled, and show what is lost from class instances. For everyday data such as API responses, app state and config objects, these four rules are enough.
Common errors
These mistakes come up most often:
- Expecting methods to survive. An object with a function property throws instead of copying. Strip functions out first, or keep data and behavior in separate places.
- Expecting class instances back. A cloned
new Point(3, 4)comes back as a plain{ x: 3, y: 4 }, andinstanceof Pointisfalse. - Calling it where it does not exist. Older Node.js versions (before 17) and old browsers have no global
structuredClone, so the call fails with aReferenceError. - Using it for a one-level copy. If nothing is nested, spread is simpler and faster.
Exercise
Given const a = { list: [1, 2], when: new Date(0) }; const b = structuredClone(a); b.list.push(3);, what do a.list.length, b.when instanceof Date and a.when === b.when evaluate to?
Show answer
a.list.length is 2 because the array was cloned. b.when instanceof Date is true because Date keeps its type. a.when === b.when is false because the Date is a new object.
Exercise
You run structuredClone({ name: 'x', save() {} }). What happens, and why?
Show answer
It throws a DataCloneError. The method save is a function, and the structured clone algorithm cannot copy functions, so it raises an error rather than silently dropping the property.