Skip to the content

Lesson 80 of 296

Deep clone and deep equal

On this page

The task

"Write deepClone(value) that makes a full independent copy." And: "Write deepEqual(a, b) that compares two values by their contents."

What the interviewer is checking

  • Recursion: a function that calls itself for each nested level.
  • Types: primitives, arrays, objects, dates, Maps, Sets.
  • Circular references.
  • Edge cases: null, NaN, different key counts, arrays vs objects.

Questions to ask first

  • "Which types must I support? Plain objects and arrays only, or also Dates, Maps, Sets and class instances?"
  • "Can there be circular references?"
  • "Should functions be copied or shared?"

deepClone: the basic idea

  1. If the value is a primitive (or null), return it. Primitives cannot be changed, so no copy is needed.
  2. If it is an array, make a new array and deep clone every item.
  3. If it is an object, make a new object and deep clone every property.

Handling circular references

const a = { name: "A" };
a.self = a;

A simple recursive clone would loop forever on a.self. The fix: remember every object already copied in a WeakMap (original to copy). If we meet the same original again, return its existing copy.

The full solution

function deepClone(value, seen = new WeakMap()) {
  if (value === null || typeof value !== "object") return value;
  if (seen.has(value)) return seen.get(value);

  if (value instanceof Date) return new Date(value.getTime());
  if (value instanceof RegExp) return new RegExp(value.source, value.flags);

  if (value instanceof Map) {
    const copy = new Map();
    seen.set(value, copy);
    for (const [k, v] of value) copy.set(deepClone(k, seen), deepClone(v, seen));
    return copy;
  }

  if (value instanceof Set) {
    const copy = new Set();
    seen.set(value, copy);
    for (const v of value) copy.add(deepClone(v, seen));
    return copy;
  }

  const copy = Array.isArray(value) ? [] : Object.create(Object.getPrototypeOf(value));
  seen.set(value, copy);
  for (const key of Reflect.ownKeys(value)) {
    copy[key] = deepClone(value[key], seen);
  }
  return copy;
}
  • We save the copy in seen before cloning its children. That way, if a child points back to the parent, the copy is already there.
  • Object.create(Object.getPrototypeOf(value)) keeps the prototype, so class instances keep their methods (unlike structuredClone).
  • Reflect.ownKeys includes symbol keys as well as string keys.
  • Functions are returned as they are (shared), because typeof fn is "function", not "object".

Test it

const original = { d: new Date(0), list: [1, { x: 2 }], tags: new Set(["a"]) };
original.self = original;

const copy = deepClone(original);
copy === original                 false
copy.self === copy                true  (circular reference preserved)
copy.list[1] === original.list[1] false (nested object copied)

deepEqual

Rules:

  1. If Object.is(a, b) is true, they are equal. This covers identical primitives, the same object, and NaN with NaN.
  2. If either is not an object (or is null), they are not equal (we already know they are not identical).
  3. Different prototypes (for example an array and an object) are not equal.
  4. Dates: compare their times.
  5. Same number of own keys, and every key in a exists in b with a deep-equal value.
function deepEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
    return false;
  }
  if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
  if (a instanceof Date) return a.getTime() === b.getTime();

  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;

  for (const key of keysA) {
    if (!Object.hasOwn(b, key)) return false;
    if (!deepEqual(a[key], b[key])) return false;
  }
  return true;
}

Test it

deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] })    true
deepEqual({ a: 1 }, { a: 1, b: 2 })                      false
deepEqual([1, 2], { 0: 1, 1: 2 })                        false (different prototypes)
deepEqual(NaN, NaN)                                      true
deepEqual({ a: undefined }, { b: undefined })            false (different keys)
deepEqual(new Date(5), new Date(5))                      true

The Object.hasOwn check matters: without it, { a: undefined } and { b: undefined } would look equal, because b.a is also undefined.

Cost

Both are O(n) in time and memory, where n is the total number of values inside the structure.

Follow-up questions

  • "Why not just use JSON.stringify(a) === JSON.stringify(b)?" Key order changes the result; undefined, functions, dates, Maps and Sets are lost or changed (Lesson 63).
  • "Extend deepEqual to Maps and Sets." Compare sizes, then compare entries.
  • "What about circular references in deepEqual?" Track pairs already being compared in a WeakMap to avoid infinite recursion.
  • "What does structuredClone do differently?" It handles most built-in types and circular references, but throws on functions and loses class prototypes.

Common mistakes

  • Forgetting typeof null === "object".
  • Treating arrays as plain objects without keeping them arrays.
  • Not handling circular references, causing a stack overflow.
  • In deepEqual, only checking keys of a, so b with extra keys passes.

How to say it in an interview

"deepClone returns primitives as they are, and recursively copies arrays and objects. I keep a WeakMap from originals to copies, filled before recursing, so circular references and shared references are preserved without infinite loops, and I handle Date, RegExp, Map and Set specially. deepEqual first uses Object.is, which also handles NaN, then requires both to be non-null objects with the same prototype and the same own keys, comparing each value recursively. Both are linear in the size of the data."

Key words

WordMeaning
RecursionA function calling itself for smaller parts
Base caseThe condition where recursion stops
Circular referenceAn object that refers back to itself
WeakMapA Map with object keys that does not keep them alive
Structural equalityEqual by contents, not by reference

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.