Deep Copy

Term side of the Card.
Topic: Basics
Unit title: Deep Copy
Categories: Concept
Explanation side of the Card

Explanation: The process of creating a new object that is a complete copy of an existing object, including all nested objects. It ensures that changes to the new object don't affect the original object.

Example

Wrongjs
const copy = JSON.parse(JSON.stringify(order));
copy.createdAt.getTime(); // TypeError
Rightjs
const copy = structuredClone(order);
copy.createdAt.getTime(); // works

structuredClone() keeps dates, maps, sets and cycles that a JSON round trip breaks.

Common mistakes

  • Losing Date, Map or undefined values after a JSON round trip.
  • A DataCloneError when the object contains a function.

Key points

  • Deep copies use structuredClone(), not JSON.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.

Analytics cookiesWe'd like to use analytics cookies to see which pages are useful. They're set only if you accept. Privacy Policy