Sub topic 12
Choosing the Right Way to Copy
This chapter assumes you have read the earlier chapters. You should know how references differ from values, what spread and Object.assign copy, what a JSON round-trip loses, and how structuredClone handles supported types, circular references and DataCloneError. The goal here is to combine that knowledge into one way of deciding how to copy a value.
Start with the question "what must be independent?"
Every copy answers one question: which parts of the original must stop being shared? The answer tells you how deep the copy has to go.
- If you only replace top-level properties, a shallow copy is enough. Nested objects stay shared, but you never mutate them.
- If you mutate nested data, you need a deep copy.
- If the data must keep behavior, such as methods, prototypes or getters, a generic deep copy is not enough. You need custom code.
The options side by side
| Strategy | Depth | Keeps Date, Map, Set | Circular references | Functions and class prototypes | Typical cost |
|---|---|---|---|---|---|
| Assignment (`b = a`) | None | Shared, not copied | Shared | Shared | Free |
| Spread or `Object.assign` | Top level only | Nested ones shared | Shared | Functions copied by reference, prototype lost with spread | Very cheap |
| `JSON.parse(JSON.stringify(v))` | Full | No: Date becomes a string, Map and Set become `{}` | Throws `TypeError` | Functions dropped, prototype lost | Moderate |
| `structuredClone(v)` | Full | Yes | Preserved | Functions throw `DataCloneError`, prototype lost | Moderate |
| Custom clone method | You decide | You decide | You decide | Preserved if you write it that way | Your code to maintain |
The JSON round-trip still has one legitimate use. If the value is going to be sent as JSON anyway, round-tripping it shows you exactly what the receiver will get. As a general way to copy, structuredClone replaces it.
A decision path
Mixing strategies in one copy
Real data is often mixed. You can use structuredClone for the plain parts and custom code for the parts that carry behavior. In the example below, the Point instance has to stay a Point, while the Set only needs an independent copy.
class Point {
constructor(x, y) { this.x = x; this.y = y; }
clone() { return new Point(this.x, this.y); }
distanceTo(other) { return Math.hypot(this.x - other.x, this.y - other.y); }
}
const state = {
origin: new Point(0, 0),
visited: new Set(['home']),
history: [{ at: new Date(0), label: 'start' }]
};
const copy = {
origin: state.origin.clone(),
visited: structuredClone(state.visited),
history: structuredClone(state.history)
};
console.log(copy.origin instanceof Point); // true
console.log(copy.origin.distanceTo(new Point(3, 4))); // 5
copy.visited.add('work');
console.log(state.visited.has('work')); // false
console.log(copy.history[0].at instanceof Date); // trueFailing loudly instead of copying wrongly
When you clone data you don't control, such as plugin state or values passed in by callers, wrap the call. A clear error at the point of copying is easier to debug than a half-copied object that breaks later.
function cloneOrExplain(value, label) {
try {
return structuredClone(value);
} catch (err) {
if (err.name === 'DataCloneError') {
throw new Error(`${label} contains a value that cannot be cloned: ${err.message}`);
}
throw err;
}
}
console.log(cloneOrExplain({ a: [1, 2] }, 'config')); // { a: [ 1, 2 ] }
try {
cloneOrExplain({ handler() {} }, 'config');
} catch (err) {
console.log(err.message.startsWith('config contains')); // true
}Common mistakes
- Using spread and then mutating a nested array. The original changes too.
- Using a JSON round-trip on data that holds dates. You get strings back, and comparisons fail without any error.
- Calling
structuredCloneon a class instance and then calling its methods. The copy is a plain object, so the method call throws aTypeError. - Catching every error from
structuredCloneand returning the original. The caller then believes it has an independent copy when it doesn't.
Exercise
You have { createdAt: new Date(), tags: new Set(['x']), settings: { theme: 'dark' } } and your code changes settings.theme and adds tags on the copy. Which strategy fits, and why are spread and a JSON round-trip wrong here?
Show answer
Use structuredClone. Spread would leave settings and tags shared, so the edits would reach the original. A JSON round-trip would turn createdAt into a string and tags into an empty object. structuredClone keeps the Date and Set types and makes every nested part independent.
Exercise
An object holds a Cart class instance whose total() method you call on the copy, plus a plain array of line items. How would you copy it?
Show answer
Give Cart its own clone method, or construct a new Cart from the copied data, so the prototype and total() survive. Use structuredClone, or a custom clone of the items inside that method, for the plain line-item array. structuredClone alone would return a plain object without total().