#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.

How to solve it

Copying all the way down

A shallow copy — spread, Object.assign, slice — copies the top level and shares everything below it. Mutating copy.nested.value changes the original, which is the bug this exists to prevent.

Approach

Recurse into objects and arrays, and remember what you have already copied.

Implementation

JSfile.javascript
1function deepClone(value, seen) { 2 seen = seen || new Map(); 3 if (value === null || typeof value !== 'object') return value; 4 if (seen.has(value)) return seen.get(value); 5 if (value instanceof Date) return new Date(value.getTime()); 6 if (value instanceof Map) { 7 const copy = new Map(); 8 seen.set(value, copy); 9 value.forEach((v, k) => copy.set(k, deepClone(v, seen))); 10 return copy; 11 } 12 if (value instanceof Set) { 13 const copy = new Set(); 14 seen.set(value, copy); 15 value.forEach((v) => copy.add(deepClone(v, seen))); 16 return copy; 17 } 18 const copy = Array.isArray(value) ? [] : {}; 19 seen.set(value, copy); 20 Object.keys(value).forEach((k) => { copy[k] = deepClone(value[k], seen); }); 21 return copy; 22}

Worth knowing

The cycle guard is the interesting part. A Map from original to copy, checked first and written before the children are filled in, is what lets a self-referencing object terminate: by the time the recursion comes back around, the copy is already registered.

JSON.parse(JSON.stringify(x)) is the one-liner everyone reaches for. It loses Date (becomes a string), Map, Set, undefined and functions, and throws outright on a cycle. structuredClone handles all of that natively and is the right answer in production — it still throws on functions, which is worth saying out loud.

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

Deep Freeze an Object

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

JavaScript · ES6 — Pratik Rai ·

JavaScript

Deep Equality

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

JavaScript · ES6 — Pratik Rai ·

JavaScript

Array.prototype.groupBy

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

JavaScript · ES6 — Pratik Rai ·