JavaScriptMedium
Deep clone an object
In production use structuredClone(value); in an interview, write a recursive clone that handles primitives, arrays, plain objects, Date, Map, Set and circular references (with a WeakMap of already-cloned objects), and preserves prototypes if required.
Building the recursive version
- Primitives and functions: return as-is (functions are usually shared, not copied).
- Circular references: keep a
WeakMapfrom original → clone; if you have seen the object, return its clone. Without this, cycles cause infinite recursion. - Special types:
Date(copy the time),RegExp(source and flags),MapandSet(clone keys/values recursively). - Arrays and objects: create the container, register it in the map before recursing, then copy each own key (use
Reflect.ownKeysto include symbols). - Prototype:
Object.create(Object.getPrototypeOf(obj))keeps class instances' methods working.
Comparing the options
| Cycles | Date/Map/Set | Functions | Class prototype | |
|---|---|---|---|---|
structuredClone | Yes | Yes | Throws | Lost (plain object) |
JSON.parse(JSON.stringify()) | Throws | Lost/wrong | Dropped | Lost |
| Custom recursive | Yes | Yes (if handled) | Shared | Kept (if handled) |
Lodash cloneDeep | Yes | Yes | Shared | Kept |
Things to mention
- Getters are evaluated into plain values by simple implementations.
- Very deep structures can overflow the stack; an iterative version fixes that.
- Deep cloning large data is expensive; for state updates prefer copying only the changed path.
Code example
js
1function deepClone(value, seen = new WeakMap()) {2 if (value === null || typeof value !== "object") return value; // primitives and functions3 if (seen.has(value)) return seen.get(value); // circular reference45 if (value instanceof Date) return new Date(value.getTime());6 if (value instanceof RegExp) return new RegExp(value.source, value.flags);78 if (value instanceof Map) {9 const copy = new Map();10 seen.set(value, copy);11 value.forEach((v, k) => copy.set(deepClone(k, seen), deepClone(v, seen)));12 return copy;13 }14 if (value instanceof Set) {15 const copy = new Set();16 seen.set(value, copy);17 value.forEach((v) => copy.add(deepClone(v, seen)));18 return copy;19 }2021 const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value)); // keep prototype22 seen.set(value, copy); // register BEFORE recursing23 for (const key of Reflect.ownKeys(value)) copy[key] = deepClone(value[key], seen);24 return copy;25}2627class Point {28 constructor(x, y) { this.x = x; this.y = y; }29 length() { return Math.hypot(this.x, this.y); }30}3132const original = {33 date: new Date("2026-01-01"),34 tags: new Set(["a", "b"]),35 lookup: new Map([["k", { deep: true }]]),36 point: new Point(3, 4),37 list: [1, { nested: [2, 3] }],38 [Symbol("id")]: 7,39};40original.self = original; // cycle4142const copy = deepClone(original);43copy.list[1].nested.push(99);44copy.lookup.get("k").deep = false;4546console.log(original.list[1].nested, original.lookup.get("k").deep); // [2, 3] true - untouched47console.log(copy.self === copy, copy.date instanceof Date, copy.tags.has("b")); // true true true48console.log(copy.point.length(), copy.point instanceof Point); // 5 true - prototype kept49console.log(Object.getOwnPropertySymbols(copy).length); // 1
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.