AceDevHub
Intermediate JavaScript Interview QuestionsIntermediateComparison

JavaScript · Question 58

How is structuredClone() different from JSON.parse(JSON.stringify(...)) for deep copying?

Direct answer

structuredClone uses the structured clone algorithm and supports cyclic graphs and many built-in data types that JSON loses, but it still cannot clone every JavaScript value and should not be treated as a way to preserve arbitrary executable object behavior.

structuredClone(value) is usually a much better built-in choice than a JSON round-trip when the goal is to duplicate supported in-memory data.

  • It can preserve cycles and supports many structured data types such as Date, Map, Set, typed arrays, and ArrayBuffer.
  • Functions and DOM nodes are not general cloneable data values and can cause cloning to fail.
  • Structured cloning is about data, not preserving arbitrary class behavior, accessors, property descriptors, or every custom prototype relationship exactly as authored.
  • Transferable objects can sometimes be transferred rather than copied when using APIs/options that support transfer lists.

For immutable application state, you often do not need to deep-clone an entire graph. Copying only the path being changed is usually cheaper and preserves structural sharing.