Home
← All questions

How to do a deep copy? JSON.stringify/parse pitfalls in JavaScript

MediumPremiumJavaScript

JavaScript interview practice: Implement deep copy and explain the disadvantages of JSON.stringify + JSON.parse.

Answer

JSON.parse(JSON.stringify(obj)) is the quick deep copy, but it drops/breaks:

  • undefined, functions, and symbols (omitted).
  • Date becomes a string, Map/Set become {}.
  • NaN/Infinity become null.
  • Circular references throw.
  • BigInt throws.

Use structuredClone(obj) (modern, handles cycles, Date, Map/Set) or a manual recursive copy.

Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium