Sub topic 12
Choosing the Right Way to Copy
This chapter assumes you have worked through the earlier chapters. You should know how references differ from values and how shallow copies share nested data. You should also know what a JSON round-trip loses, what structuredClone keeps and drops, and which values make it throw a DataCloneError. Here those pieces become a decision process you can apply to real data.
No single copying method is best everywhere. Each one trades correctness, speed, and portability differently. The right choice depends on three questions:
- What shape is the data, and which types does it contain?
- Why do you need a copy at all?
- Where will the code run?
Start With Why You Are Copying
Many copies in real code are unnecessary. Before you pick a method, decide what problem the copy solves.
| Reason for copying | What you actually need |
|---|---|
| Update state without mutating it (React, Redux, signals) | A new object along the changed path only. Unchanged branches can stay shared |
| Hand data to code you do not trust not to mutate it | A full deep copy, or a frozen object |
| Take a snapshot for undo history or test fixtures | A full deep copy that keeps types such as `Date` and `Map` |
| Send data to a server or store it as text | Serialization, which is usually JSON |
| Send data to a worker or another window | Nothing extra. `postMessage` already structured-clones the data |
| Keep a template object and stamp out instances | A factory function, which is often better than a copy |
The last two rows are easy to miss. Calling structuredClone on data right before postMessage copies it twice. When you only need fresh objects from a template, a function that returns a new literal is clearer and faster than cloning:
function makeDefaultSettings() {
return { theme: 'light', shortcuts: new Map(), recent: [] };
}
const a = makeDefaultSettings();
const b = makeDefaultSettings();
console.log(a.recent === b.recent); // falseThe Four Main Strategies
Each strategy behaves in a predictable way.
Shallow copy with spread or Object.assign
A shallow copy creates one new top-level container. Every nested value is still shared with the original. It costs almost nothing, and it is the right tool for immutable updates. In an immutable update you copy each level along the path you change and share everything else. This reuse of unchanged parts is called structural sharing.
const state = {
user: { name: 'Ada', prefs: { theme: 'dark' } },
tags: ['a', 'b']
};
const next = {
...state,
user: { ...state.user, name: 'Grace' }
};
console.log(state.user.name); // 'Ada'
console.log(next.user.name); // 'Grace'
console.log(next.tags === state.tags); // true (shared, unchanged)
console.log(next.user.prefs === state.user.prefs); // true (shared, unchanged)Structural sharing helps libraries detect changes, because a reference comparison (===) tells you whether a branch changed. A deep copy of the whole state would defeat this. Every branch would become a new object, and every component would think its data had changed.
JSON round-trip
JSON.parse(JSON.stringify(value)) produces plain objects, arrays, strings, numbers, booleans, and null. It works without problems only when the data already fits that model. It quietly converts or drops many values:
Datebecomes a string.undefinedproperties are dropped.NaNandInfinitybecomenull.MapandSetbecome{}.
It throws a TypeError on circular references and on BigInt.
JSON is still a good choice in one case: when the copy is going to become JSON anyway. Examples are building a request body, writing to localStorage, or checking that a value serializes the way your API expects. In those cases the lossy conversion is the behavior you want, and doing it early surfaces problems sooner.
structuredClone
structuredClone is the default choice for a full, independent deep copy of data. It keeps Date, RegExp, Map, Set, typed arrays, ArrayBuffer, Blob, errors, BigInt, NaN, and undefined. It also keeps circular and shared references intact. Its limits are the ones covered in earlier chapters:
- Functions and DOM nodes throw
DataCloneError. - Class instances come back as plain objects.
- Getters are replaced by their current values.
- Non-enumerable properties, symbol keys, and private fields are not copied.
Custom cloning
When the data contains behavior, you need code that knows how to rebuild it. Behavior here means class instances with methods, private fields, functions, or resources such as sockets. That code can be a clone() method on a class, a hand-written function for one data shape, or a library such as Lodash's cloneDeep. Lodash keeps prototypes in some cases where structuredClone does not, but it has its own rules for what it copies. Read its documentation before you rely on it for class instances.
A Decision Flow
Comparison at a Glance
| Feature | Spread / `Object.assign` | JSON round-trip | `structuredClone` | Custom clone |
|---|---|---|---|---|
| Nested objects independent | No | Yes | Yes | Yes, if written to |
| `Date`, `Map`, `Set` keep their type | Shared, not copied | No | Yes | Yes, if written to |
| `undefined`, `NaN`, `BigInt` | Kept | Dropped, `null`, or throws | Kept | Yes, if written to |
| Circular references | Shared | Throws `TypeError` | Kept | Needs a `WeakMap` of visited objects |
| Functions | Shared | Dropped | Throws `DataCloneError` | You decide |
| Class prototype | Lost with spread | Lost | Lost | Kept |
| Getters | Called, value copied | Called, value copied | Called, value copied | Can be kept |
| Relative cost | Very low | High for large data | Moderate | Varies |
Restoring Class Instances
A common middle ground is to use structuredClone for the data and then put the prototype back. This works when every piece of an instance's state lives in ordinary public own properties:
class Point {
constructor(x, y) { this.x = x; this.y = y; }
get length() { return Math.hypot(this.x, this.y); }
}
function cloneInstance(instance) {
const copy = structuredClone(instance);
return Object.setPrototypeOf(copy, Object.getPrototypeOf(instance));
}
const p = new Point(3, 4);
const q = cloneInstance(p);
console.log(q instanceof Point); // true
console.log(q.length); // 5
console.log(q === p); // falseThis trick only fixes the top level. Nested instances, such as an array of Point objects, are still plain objects inside the copy. It also fails with private fields:
class Counter {
#count = 0;
increment() { this.#count += 1; return this.#count; }
}
const original = new Counter();
const copy = Object.setPrototypeOf(structuredClone(original), Counter.prototype);
try {
copy.increment();
} catch (err) {
console.log(err instanceof TypeError); // true: the copy has no #count slot
}When a class has private fields or any state that is not plain data, give the class its own clone() method. Only the class can see its private fields, so only the class can copy them:
class Counter {
#count = 0;
increment() { this.#count += 1; return this.#count; }
clone() {
const next = new Counter();
next.#count = this.#count;
return next;
}
}
const c1 = new Counter();
c1.increment();
const c2 = c1.clone();
console.log(c2.increment()); // 2
console.log(c1.increment()); // 2 (independent)Handling Mixed Data Safely
Sometimes data arrives from elsewhere and you cannot be sure it is cloneable. A small wrapper turns a confusing error into one that explains itself:
function safeClone(value, label = 'value') {
try {
return structuredClone(value);
} catch (err) {
if (err && err.name === 'DataCloneError') {
throw new Error(`${label} contains something structuredClone cannot copy: ${err.message}`, { cause: err });
}
throw err;
}
}
console.log(safeClone({ a: [1, 2] })); // { a: [ 1, 2 ] }
try {
safeClone({ handler() {} }, 'config');
} catch (err) {
console.log(err.message.startsWith('config contains')); // true
}Do not hide the error by quietly removing functions before cloning. If an object has a function in it, the code that uses the copy probably expects that function to work. A copy missing the function is a bug that appears later, far from where it started.
Common Errors When Choosing
- Deep cloning on every state update. This breaks the reference checks that rendering libraries rely on and wastes memory. Use spread along the changed path instead.
- Using JSON "because it is fast". For data that is not already JSON-shaped, it corrupts values. Recent engines run
structuredCloneat speeds comparable to JSON for typical object graphs. If speed matters, measure it on your own data. - Assuming
instanceofstill works on a copy. AfterstructuredClone, it does not, and methods are gone. Check whether your data holds class instances before you choose. - Cloning before
postMessageor an IndexedDBput. Both already run the structured clone algorithm, so the extra copy is wasted work. - Forgetting about older runtimes.
structuredCloneis a global in Node.js 17 and later, in all current major browsers (since early 2022), and in Deno and Bun. Older targets need feature detection and a fallback. - Using
transferby mistake. Transferring anArrayBufferdetaches the original. Use it only when the sending code no longer needs the buffer.
Putting It Together
For most application code the rules come down to this:
- Use spread for immutable updates.
- Use
structuredClonefor snapshots and defensive copies of data. - Use JSON only when the destination is JSON.
- Write custom clones for objects that carry behavior.
When none of these fits cleanly, the data usually mixes plain data with behavior. Separating the two usually works better than looking for a smarter cloning function.
Exercise
A Redux reducer receives state shaped like { items: [...], filter: { text: '' } } and must set filter.text to 'abc'. A teammate writes const next = structuredClone(state); next.filter.text = 'abc'; return next;. What problem does this cause, and what should the reducer return instead?
Show answer
structuredClone gives every branch a new reference, including items, which did not change. Selectors and components that compare references see items as changed and recompute or re-render for no reason. Return { ...state, filter: { ...state.filter, text: 'abc' } } instead. Only the changed path gets new objects, and items stays shared.
Exercise
You need an undo history for an editor whose document is { createdAt: Date, layers: Map<string, { name: string, pixels: Uint8Array }> }. Which copying strategy fits, and why not a JSON round-trip?
Show answer
Use structuredClone. It keeps the Date as a Date, the Map as a Map, and each Uint8Array as a typed array with its own copied memory, so every snapshot is fully independent. A JSON round-trip would turn createdAt into a string. It would turn the Map into {}, losing every layer, and it would turn each Uint8Array into an object with index keys.
Exercise
A Shape class stores its vertices in a private field #points and has an area() method. Will Object.setPrototypeOf(structuredClone(shape), Shape.prototype) give a working copy? If not, what should you do?
Show answer
No. structuredClone does not copy private fields, so the copy has no #points slot, and calling area() throws a TypeError when it reads this.#points. Add a clone() method to Shape that builds a new instance and copies #points itself (for example, by mapping each point to a new object). Only code inside the class can read and write the private field.