Deep clone a nested structure
The spread operator copies one level. Edit copy.address.city and you have just edited the original too, which is how undo stacks and form drafts quietly corrupt state. JSON.parse(JSON.stringify(x)) is the usual escape hatch, and it throws on circular references and destroys Dates.
Implement deepClone(value) returning a copy where every nested plain object and array is a new object — nothing in the output shares a reference with the input. Primitives come through unchanged. A Date becomes a fresh Date with the same time value.
Two reference rules matter: if the same object appears at two places in the input, it must appear as one shared object at both places in the output; and a structure that refers to itself must clone without infinite recursion, with the clone referring to itself in the same way.
Arguments
valueany- A primitive, plain object, array, Date, or any nesting of those.
Returns
any — A structural copy of value with no shared references.
Examples
const source = { a: { b: [1, 2] } };
const copy = deepClone(source);
copy.a.b.push(3);
// source.a.b is still [1, 2] — the inner array was clonedconst node = { n: 1 };
node.self = node;
const copy = deepClone(node);
// copy.n === 1, copy.self === copy, copy !== nodeA self-referential structure survives — the clone refers to itself the same way.
What it has to do
- Recursively copy plain objects and arrays so nothing is shared with the input.
- Return primitives unchanged.
- Clone a
Dateinto a newDatewith the same time value. - Preserve sharing: one object appearing twice in the input appears as one object twice in the output.
- Handle circular references without infinite recursion.
Stuck? The javascript course covers everything this challenge needs.
- 1.copies nested values independently
- 2.produces an equal but non-identical structure
- 3.clones a Date into a new Date
- 4.survives a circular reference
- 5.preserves a shared reference
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.