#Objects#Recursion

Deep Clone

Copy a nested structure so nothing is shared — including the cases that break a naive recursion.

By Pratik RaiMedium

Write deepClone(value) returning a copy that shares no references with the input.

Handle plain objects and arrays, keep Date, Map and Set intact rather than flattening them, and do not hang on a structure that contains itself.

Examples

Input:

JSfile.javascript
1const original = { list: [1, { deep: true }] }; 2const copy = deepClone(original); 3copy.list[1] === original.list[1];

Output:

false

The nested object was copied, not referenced.

Constraints

  • Values may be nested arbitrarily deep
  • Structures may contain cycles

Notes

  • JSON.parse(JSON.stringify(x)) is the one-liner everyone reaches for; it loses Dates, Maps, Sets and undefined, and throws on a cycle.
  • structuredClone handles all of the above natively — and still throws on functions.

Goal: Produce a copy that shares nothing with the original, cycles included.

Frequently asked questions

What is the difference between a shallow and a deep copy?
A shallow copy duplicates the top level and shares everything nested, so mutating a nested value changes the original. A deep copy duplicates every level, leaving nothing shared.
What is wrong with JSON.parse(JSON.stringify(obj))?
It loses `Date` objects (they become strings), `Map`, `Set`, `undefined` and functions, and it throws outright on a circular reference. It is quick and fine for plain JSON-shaped data, and wrong for anything else.
How do you handle circular references?
Keep a `Map` from each original to its copy, check it before recursing, and register the copy before filling in its children. When the recursion comes back around, the copy is already there and the cycle terminates.
Should you use structuredClone in production?
Usually yes. It is built into modern browsers and Node, handles Dates, Maps, Sets, typed arrays and cycles natively, and is faster than a hand-written walk. It throws on functions and DOM nodes, which is worth knowing before you rely on it.

Related Challenges

Continue learning with these related challenges

View All
JavaScript

Make Object Immutable

Freeze an object all the way down, because Object.freeze only handles the top level.

JavaScript · ES6Pratik Rai ·

JavaScript

Deep Equality

Compare two values structurally, because === only ever compares references.

JavaScript · ES6Pratik Rai ·

JavaScript

Array.prototype.groupBy

Group an array into buckets by a key function — now a real language feature as Object.groupBy.

JavaScript · ES6Pratik Rai ·