JavaScriptMedium
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
- If
Object.is(a, b), returntrue(handlesNaNand identical references). - If either is not an object (or is
null), returnfalse. - Different prototypes or constructors →
false(an array is not equal to an object with numeric keys). - Special cases:
Date(comparegetTime()),RegExp(source and flags),Map(same size, each key's value deeply equal),Set(same size and members). - Compare own keys: same count, and every key in
aexists inbwith a deeply equal value.Reflect.ownKeysincludes symbols. - Cycles: keep a
WeakMapof pairs already being compared to avoid infinite recursion.
Choices to discuss
- Should
0equal-0? (Object.issays no;===says yes.) - Is key order relevant? Usually not.
- Should
undefinedproperties 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;56 // cycle guard7 if (seen.get(a) === b) return true;8 seen.set(a, b);910 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 needed20 return true;21 }2223 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}2829const 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)3233console.log(deepEqual([1, 2], { 0: 1, 1: 2 })); // false - array vs object34console.log(deepEqual({ a: undefined }, {})); // false - different keys35console.log(deepEqual(new Set([1, 2]), new Set([2, 1]))); // true36console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 })); // false - why the JSON trick fails3738// Circular structures39const 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.