Deep Copy
Example
const copy = JSON.parse(JSON.stringify(order));
copy.createdAt.getTime(); // TypeErrorconst copy = structuredClone(order);
copy.createdAt.getTime(); // worksstructuredClone() keeps dates, maps, sets and cycles that a JSON round trip breaks.
Common mistakes
- Losing
Date,Maporundefinedvalues after a JSON round trip. - A
DataCloneErrorwhen the object contains a function.
Key points
- Deep copies use
structuredClone(), notJSON.parse(JSON.stringify()). - Data passed to
structuredClone()has no functions, DOM nodes or class instances that must keep their prototype. - Only data that will be changed independently is deep copied.
Interview questions
Why not use JSON.parse(JSON.stringify()) for deep copy?
It turns dates into strings, drops undefined and functions, loses Map and Set, and throws on circular references.
Does structuredClone copy class instances?
It copies own data properties, but the result is a plain object without the class prototype or methods.