Difficulty: Intermediate
What are the different ways to clone objects in JavaScript (spread, Object.assign, JSON, structuredClone), and what are the limitations of each?
JavaScript has two kinds of copies: a shallow copy duplicates only the top-level properties, so nested objects are still shared, while a deep copy duplicates every level. Spread ({...obj}, [...arr]) and Object.assign make shallow copies. For deep copies, the modern built-in is structuredClone(value), available in all current browsers and Node.js 17+, which handles nested objects, Date, Map, Set and circular references; the older JSON.parse(JSON.stringify(obj)) trick works only for plain JSON-safe data.
const copy = { ...order } creates a new outer object, but copy.address === order.address is still true. Changing copy.address.city changes the original too. This is the bug behind many "state changed unexpectedly" issues in React and Redux, where you must create new objects at every level you modify.
| Method | Depth | Dates | Map / Set | Functions | undefined | Circular refs | Class prototype |
|---|---|---|---|---|---|---|---|
Spread / Object.assign | Shallow | Shared reference | Shared reference | Copied as reference | Kept | Fine (shallow) | Lost (plain object) |
JSON.parse(JSON.stringify()) | Deep | Become strings | Become {} | Dropped | Dropped from objects, null in arrays | Throws TypeError | Lost |
structuredClone() | Deep | Real Date | Real Map / Set | Throws DataCloneError | Kept | Supported | Lost |
Lodash cloneDeep | Deep | Real Date | Real Map / Set | Kept as reference in objects | Kept | Supported | Preserved |
More JSON pitfalls: NaN and Infinity become null, BigInt throws, and Symbol keys and values disappear.
structuredClone uses the same structured clone algorithm the browser uses for postMessage, IndexedDB and Web Workers. It supports primitives (including BigInt), plain objects, arrays, Date, RegExp, Map, Set, ArrayBuffer, typed arrays, Blob, File, ImageData and most Error types, and it preserves shared and circular references.
It does not:
DataCloneError)class Order instance comes back as a plain object without methodsIt also accepts a transfer option to move ArrayBuffers instead of copying them, which is how you hand large binary data to a worker cheaply.
{...state, user: {...state.user, name}}) or Immer. A deep clone of the whole state defeats memoization.structuredClone.localStorage: you need JSON anyway, so JSON round-tripping is fine if you know its limits.clone() method or copy constructor.Deep cloning large objects is not free. If you clone on every keystroke or render, consider whether you need a copy at all.
const order = {
id: 'ord_77',
address: { city: 'Bengaluru' },
placedAt: new Date('2026-01-15T10:00:00Z'),
};
const shallow = { ...order };
shallow.address.city = 'Mumbai';
console.log(order.address.city); // original changed!
const deep = structuredClone(order);
deep.address.city = 'Pune';
console.log(order.address.city, deep.address.city);
console.log(deep.placedAt instanceof Date);
const node = { name: 'a' };
node.self = node;
const copy = structuredClone(node); // circular reference is fine
console.log(copy.self === copy);
Spread shares the nested address object, so mutating the copy leaks into the original. structuredClone duplicates every level, keeps Date as a Date and preserves the circular reference.
const data = {
when: new Date(0),
tags: new Set(['veg']),
missing: undefined,
ratio: NaN,
greet() { return 'hi'; },
};
const viaJson = JSON.parse(JSON.stringify(data));
console.log(viaJson);
try {
structuredClone(data);
} catch (e) {
console.log(e.name); // functions cannot be cloned
}
class Money {
constructor(paise) { this.paise = paise; }
toRupees() { return this.paise / 100; }
}
const cloned = structuredClone(new Money(1500));
console.log(cloned instanceof Money, typeof cloned.toRupees);
JSON turns the Date into a string, the Set into an empty object, NaN into null, and drops undefined and the function. structuredClone refuses functions and returns class instances as plain objects without their methods.
Shallow Copy, Deep Clone, structuredClone, JSON.parse(JSON.stringify()), Structured Clone Algorithm