JavaScript Deep Copy: structuredClone vs JSON vs Spread, Tested
A JavaScript deep copy duplicates an object and everything nested inside it, so changing the copy never touches the original. Compare spread, Object.assign, the JSON trick, structuredClone and a custom function on dates, Maps, Sets, BigInt, circular references and classes, with real Node.js output and timings.
- Spread (
{...obj}) andObject.assignare shallow: nested objects stay shared. - The JSON trick turns Dates into strings, Sets and Maps into
{}, dropsundefined, turnsNaNintonull, and throws on BigInt and cycles. structuredClonekeeps Dates, Maps, Sets, BigInt,undefined,NaNand circular references, but drops class prototypes and throws on functions.- In our Node.js 24 test, the JSON trick was actually faster for plain data; choose by correctness first.
You copy an order object, change the quantity in the copy, and the original order changes too. Every JavaScript developer hits this once. Objects are assigned by reference, and most “copy” techniques only copy the top level. A JavaScript deep copy creates fully independent nested data, and since 2022 the language has a built-in way to do it. Each technique still has trade-offs, so we tested them side by side.
All examples ran in Node.js v24.22.1 and the output is shown as printed. structuredClone works the same in modern browsers. If spread syntax is new to you, start with our spread operator guide.
Shallow copy vs deep copy
A shallow copy creates a new outer object but copies references to anything nested inside, so both objects point at the same inner arrays and objects. A deep copy recursively copies every level. Primitive values such as numbers and strings are always copied, because they are immutable.
Our test object
const order = {
id: 1,
items: [{ sku: "A1", qty: 1 }],
created: new Date("2026-11-22T10:00:00Z"),
tags: new Set(["new"]),
meta: new Map([["src", "web"]]),
note: undefined,
total: NaN,
big: 10n ** 20n,
};
It deliberately contains the types that break naive copies: nested arrays, a Date, a Set, a Map, an undefined property, NaN and a BigInt.
Spread and Object.assign: shallow only
const s = { ...order };
s.items[0].qty = 99;
console.log(order.items[0].qty); // 99 (original changed!)
const o2 = Object.assign({}, order);
console.log(o2.items === order.items); // true (same array)
Both create a new top-level object, so s.id = 2 would not affect order. But items is the same array in both, so changing a nested item changes the original. Shallow copies are perfect for flat objects and for immutable update patterns where you copy each level you change, as in { ...order, items: [...order.items, newItem] }.
The JSON trick: JSON.parse(JSON.stringify(x))
JSON.parse(JSON.stringify(order));
// TypeError: Do not know how to serialize a BigInt
const { big, ...noBig } = order;
const j = JSON.parse(JSON.stringify(noBig));
typeof j.created // 'string'
JSON.stringify(j.tags) // '{}'
JSON.stringify(j.meta) // '{}'
"note" in j // false
j.total // null
Serialising to text and back produces new objects at every level, which is why this trick was popular for years. But it only understands JSON’s types. Our Date became a string, the Set and Map became empty objects, the undefined property disappeared, NaN became null, and BigInt threw an error. Functions are silently dropped, and a circular reference throws TypeError. It is safe only for data that is already plain JSON, such as an API response.
structuredClone: the built-in deep copy
const sc = structuredClone(order);
sc.created instanceof Date // true
sc.tags instanceof Set // true
sc.meta.get("src") // 'web'
"note" in sc // true
sc.total // NaN
sc.big // 100000000000000000000n
sc.items[0].qty = 5;
order.items[0].qty // 1 (original untouched)
structuredClone uses the same algorithm browsers use to send data to Web Workers and store it in IndexedDB. It handles Dates, RegExps, Maps, Sets, typed arrays, ArrayBuffers, BigInt, undefined, NaN and Error objects. It is a global in modern browsers and in Node.js 17 and later, with no import or library needed.
Circular and shared references
const a = { name: "a" };
a.self = a;
const ac = structuredClone(a);
ac.self === ac // true (cycle rebuilt inside the copy)
ac.self !== a // true (not pointing at the original)
JSON.stringify(a) // TypeError (circular structure)
const shared = { x: 1 };
const two = structuredClone({ a: shared, b: shared });
two.a === two.b // true (shared reference preserved)
Real data often contains cycles, such as a parent with children that point back to the parent. structuredClone rebuilds the same graph shape inside the copy: an object referenced twice in the original is still one object referenced twice in the copy. The JSON trick fails on cycles, and on shared references it would silently create two separate copies.
What structuredClone cannot copy
structuredClone({ fn() {} });
// DataCloneError: fn() {} could not be cloned.
class Money { constructor(v) { this.v = v; } fmt() { return `₹${this.v}`; } }
const m = structuredClone(new Money(5));
m instanceof Money // false
m.constructor.name // 'Object'
typeof m.fmt // 'undefined'
Object.isFrozen(structuredClone(Object.freeze({ k: 1 }))) // false
- Functions throw a
DataCloneError. - Class instances come back as plain objects: data is copied, methods and the prototype are lost.
- Property descriptors are not kept: getters become plain values, and frozen objects come back unfrozen.
- DOM nodes cannot be cloned (use
node.cloneNode(true)), and Symbols as values throw.
If your state is plain data, these limits rarely matter. If it holds class instances, see the next section or rebuild instances from the cloned data. Our JavaScript classes guide covers prototypes.
A custom deep copy that keeps classes
function deepCopy(v, seen = new WeakMap()) {
if (v === null || typeof v !== "object") return v;
if (seen.has(v)) return seen.get(v);
if (v instanceof Date) return new Date(v);
const out = Array.isArray(v) ? [] : Object.create(Object.getPrototypeOf(v));
seen.set(v, out);
for (const k of Reflect.ownKeys(v)) out[k] = deepCopy(v[k], seen);
return out;
}
const mc = deepCopy(new Money(7));
mc instanceof Money // true
mc.fmt() // '₹7'
Keeping the prototype preserves methods, and the WeakMap handles cycles. This short version does not handle Maps, Sets or typed arrays, which is exactly why hand-written deep copy functions tend to grow bugs. Libraries such as Lodash’s cloneDeep cover more cases; we did not run Lodash here.
Comparison table
| Feature | Spread / assign | JSON trick | structuredClone |
|---|---|---|---|
| Nested objects copied | No | Yes | Yes |
| Date stays a Date | Shared | Becomes string | Yes |
| Map and Set | Shared | Become {} |
Yes |
undefined, NaN |
Yes | Dropped, null |
Yes |
| BigInt | Yes | Throws | Yes |
| Circular references | Shared | Throws | Yes |
| Functions | Shared | Dropped | Throws |
| Class prototype | Lost | Lost | Lost |
Performance
| Test (Node.js 24, best of 5) | structuredClone | JSON round trip |
|---|---|---|
| 20,000 nested objects | 26.6 ms | 14.0 ms |
| 100,000 tiny objects, one at a time | 181 ms | 53 ms |
For plain JSON-shaped data, the JSON round trip was faster in our runs, because V8’s JSON functions are heavily optimised and structuredClone does more bookkeeping for types and cycles. Older articles report the opposite for large objects, which shows how engine versions change these numbers. Either way, copying 20,000 objects took well under 30 ms. Choose the method that is correct for your data, and only optimise if profiling shows copying is a real cost.
Tip: if you deep-copy large state on every change, consider structural sharing instead: copy only the path you modify and reuse the rest.
Do you need a deep copy at all?
Often the better answer is not to mutate. Immutable update patterns copy only the levels you change:
const updated = { ...order,
items: order.items.map(i => i.sku === "A1" ? { ...i, qty: 2 } : i) };
This creates a new order and a new item while sharing everything unchanged. This is how React and Redux state updates are usually written, and it is faster than copying everything. Destructuring makes these updates shorter.
Which deep copy method should you use?
- Plain JSON data (API responses, config):
structuredClone, or the JSON trick if you also want to strip non-JSON values. - Data with Dates, Maps, Sets, BigInt or cycles:
structuredClone. - Class instances: a custom copy or a
clone()method on the class. - Flat objects or one-level updates: spread.
- Frequently updated large state: immutable updates with structural sharing.
Python developers will recognise the same split between copy.copy and copy.deepcopy; see our Python deepcopy guide.
Final thoughts
A JavaScript deep copy is only as good as its handling of your data types. Spread is shallow, the JSON trick silently corrupts Dates, Maps, Sets and special numbers, and structuredClone handles almost everything except functions and class prototypes. Make structuredClone your default, keep the JSON trick for strictly JSON data, write a custom copy when classes matter, and avoid copying altogether with immutable updates when you can.
Frequently asked questions
How do I deep copy an object in JavaScript?
Use the built-in structuredClone function, for example const copy = structuredClone(original). It copies nested objects, arrays, Dates, Maps, Sets and circular references.
Is the spread operator a deep copy?
No. Spread creates a shallow copy, so nested objects and arrays are still shared between the original and the copy.
What is wrong with JSON parse and stringify for copying?
It converts Dates to strings, turns Maps and Sets into empty objects, drops undefined and functions, turns NaN into null and throws on BigInt and circular references.
Does structuredClone copy class instances?
It copies their data but not their prototype, so the result is a plain object without the class methods. Use a custom copy or a clone method for class instances.
Is structuredClone faster than JSON?
Not always. In our Node.js 24 test the JSON round trip was faster for plain data. structuredClone is chosen for correctness, because it supports many more types.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.