Deep Clone

ObjectsRecursionImmutability

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

Example 1
Input
const original = { list: [1, { deep: true }] };
const copy = deepClone(original);
copy.list[1] === original.list[1];
Output
false
Explanation
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.

Hints

Read the full write-up for Deep Clone
</>JavaScript
Loading editor…
Test Result
Run your code, or Submit to test it