Deep compare two objects

A deep equality check compares structure and values recursively: same type, same keys and deeply equal values at every level; a solid implementation also handles NaN, dates, arrays vs objects, Map/Set and circular references.

Algorithm

  1. If Object.is(a, b), return true (handles NaN and identical references).
  2. If either is not an object (or is null), return false.
  3. Different prototypes or constructors → false (an array is not equal to an object with numeric keys).
  4. Special cases: Date (compare getTime()), RegExp (source and flags), Map (same size, each key's value deeply equal), Set (same size and members).
  5. Compare own keys: same count, and every key in a exists in b with a deeply equal value. Reflect.ownKeys includes symbols.
  6. Cycles: keep a WeakMap of pairs already being compared to avoid infinite recursion.

Choices to discuss

  • Should 0 equal -0? (Object.is says no; === says yes.)
  • Is key order relevant? Usually not.
  • Should undefined properties count ({a: undefined} vs {})? Strict equality says they differ.
  • Class instances: compare prototypes, or only data?

In practice

  • Node: util.isDeepStrictEqual; test runners: expect(a).toEqual(b) / toStrictEqual.
  • Lodash isEqual.
  • React and memoisation deliberately use shallow comparison for speed; deep comparison of big trees on every render is expensive.

JSON shortcut

JSON.stringify(a) === JSON.stringify(b) breaks on key order, undefined, dates, NaN, Maps/Sets and cycles; avoid it except for quick, known-shape checks.

Code example

js
1function deepEqual(a, b, seen = new WeakMap()) {
2 if (Object.is(a, b)) return true;
3 if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
4 if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
5
6 // cycle guard
7 if (seen.get(a) === b) return true;
8 seen.set(a, b);
9
10 if (a instanceof Date) return a.getTime() === b.getTime();
11 if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;
12 if (a instanceof Map) {
13 if (a.size !== b.size) return false;
14 for (const [k, v] of a) if (!b.has(k) || !deepEqual(v, b.get(k), seen)) return false;
15 return true;
16 }
17 if (a instanceof Set) {
18 if (a.size !== b.size) return false;
19 for (const v of a) if (!b.has(v)) return false; // primitives; extend for objects if needed
20 return true;
21 }
22
23 const keysA = Reflect.ownKeys(a);
24 const keysB = Reflect.ownKeys(b);
25 if (keysA.length !== keysB.length) return false;
26 return keysA.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k], seen));
27}
28
29const x = { id: 1, tags: ["a", "b"], meta: { created: new Date(0), score: NaN }, lookup: new Map([["k", { v: 1 }]]) };
30const y = { meta: { score: NaN, created: new Date(0) }, lookup: new Map([["k", { v: 1 }]]), tags: ["a", "b"], id: 1 };
31console.log(deepEqual(x, y)); // true (key order doesn't matter, NaN equals NaN)
32
33console.log(deepEqual([1, 2], { 0: 1, 1: 2 })); // false - array vs object
34console.log(deepEqual({ a: undefined }, {})); // false - different keys
35console.log(deepEqual(new Set([1, 2]), new Set([2, 1]))); // true
36console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 })); // false - why the JSON trick fails
37
38// Circular structures
39const c1 = { name: "loop" };
40c1.self = c1;
41const c2 = { name: "loop" };
42c2.self = c2;
43console.log(deepEqual(c1, c2)); // true

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.

Open in study app