Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Deep equality check for objects in JavaScript

91 deep equals, and the cases === cannot see

hard

Write deepEquals(a, b) that walks two values and reports whether they hold the same data. Handle nested objects and arrays, Date, Map and Set, and get NaN right. Then show the two places it still disagrees with what you might expect: an explicit undefined value, and -0.

Stuck? Three hints, smallest first
  1. 1. Start with if (a === b) return true. That one line settles every primitive and every case where both sides are the same object.
  2. 2. Number.isNaN(a) && Number.isNaN(b) is the only place === is wrong, so it is the only special case you need before the object walk.
  3. 3. An array and { 0: x, 1: y, length: 2 } hold the same data but are not the same kind of thing. Object.getPrototypeOf tells them apart in one comparison.

The answer

const deepEquals = (a, b) => {
  if (a === b) return true;                                   // primitives, and the same reference
  if (Number.isNaN(a) && Number.isNaN(b)) return true;        // the one thing === gets wrong
  if (typeof a !== 'object' || typeof b !== 'object') return false;
  if (a === null || b === null) return false;
  if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
  if (a instanceof Date) return a.getTime() === b.getTime();
  if (Array.isArray(a)) return a.length === b.length && a.every((v, i) => deepEquals(v, b[i]));
  if (a instanceof Map) {
    if (a.size !== b.size) return false;
    for (const [k, v] of a) if (!b.has(k) || !deepEquals(v, b.get(k))) return false;
    return true;
  }
  if (a instanceof Set) {
    if (a.size !== b.size) return false;
    for (const v of a) if (!b.has(v)) return false;
    return true;
  }
  const keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;
  return keys.every((k) => Object.hasOwn(b, k) && deepEquals(a[k], b[k]));
};

const joined = '2022-05-01T00:00:00.000Z';
const left = { name: 'Chidi', lga: 'Surulere', roles: ['rider', 'lead'], meta: { tier: 2, since: new Date(joined) } };
const right = { name: 'Chidi', lga: 'Surulere', roles: ['rider', 'lead'], meta: { tier: 2, since: new Date(joined) } };
const reordered = { lga: 'Surulere', meta: { since: new Date(joined), tier: 2 }, roles: ['rider', 'lead'], name: 'Chidi' };
const oneLeafOff = { ...right, meta: { ...right.meta, tier: 3 } };
const arrayLike = { 0: 'rider', 1: 'lead', length: 2 };

const stockA = new Map([['GRP-1', 2], ['GRP-2', 5]]);
const stockB = new Map([['GRP-2', 5], ['GRP-1', 2]]);
const stockShort = new Map([['GRP-1', 2]]);
const zonesA = new Set(['ikeja', 'yaba', 'lekki']);
const zonesB = new Set(['lekki', 'yaba', 'ikeja']);

const withUndefined = { id: 'AC-9', otp: undefined };
const withoutOtp = { id: 'AC-9' };

console.log('same data   :', deepEquals(left, right), '| same object:', left === right);
console.log('key order   :', deepEquals(right, reordered), '| one leaf off:', deepEquals(left, oneLeafOff));
console.log('collections :', deepEquals(stockA, stockB), deepEquals(zonesA, zonesB));
console.log('undefined   :', deepEquals(withUndefined, withoutOtp), '| JSON says:', same(withUndefined, withoutOtp));

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('two objects built separately hold the same data, and === still says no', [deepEquals(left, right), left === right], [true, false]);
test('key order is not part of the value', deepEquals(right, reordered), true);
test('one leaf out of place is enough to fail', deepEquals(left, oneLeafOff), false);
test('NaN equals itself here, which is the one place === is wrong', [deepEquals(NaN, NaN), NaN === NaN], [true, false]);
test('an array and an array-like are different kinds of thing', deepEquals(left.roles, arrayLike), false);
test('Maps compare by entries, and insertion order is not part of it', [deepEquals(stockA, stockB), deepEquals(stockA, stockShort)], [true, false]);
test('Sets compare by membership', deepEquals(zonesA, zonesB), true);
test('an explicit undefined is still a key, so the walk and JSON disagree', [deepEquals(withUndefined, withoutOtp), same(withUndefined, withoutOtp)], [false, true]);
test('0 and -0 slip through as equal, because === says they are', [deepEquals(0, -0), Object.is(0, -0)], [true, false]);

The first line does most of the work. a === b settles every number, string, boolean, null, undefined, symbol and every case where both sides are literally the same object, which means the recursive part only ever runs on two different objects. After that the shape of the function is a list of the kinds of thing JavaScript has: array, Date, Map, Set, plain object. There is no generic answer, because there is no generic way to ask an object what it contains.

The prototype check earns its place twice. It separates an array from an array-like, and it separates a plain object from a class instance with the same fields, which is usually what you want: a Naira and a bare { amount } are not the same value even when they print the same.

Two disagreements are left in on purpose. { otp: undefined } and {} are not equal here, because they have different key counts, while JSON.stringify flattens them to the same string — which is why a deep equals built on stringify quietly passes a bug through. And -0 compares equal to 0, because === says so. If that matters, swap the first line for Object.is(a, b), which separates them and handles NaN for free, letting you delete the second line.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.