← Back to JavaScript, page 5

javascript-0086 · Medium mid

How would you implement a deepEqual function that compares two values by content?

deepEqual compares primitives with Object.is semantics, then checks that both values have the same type and prototype, and compares arrays, plain objects, dates, regular expressions, Maps, and Sets recursively. It must handle NaN, key order, extra keys, and circular references, which a WeakMap of visited pairs prevents from looping forever.

Full answer

The built-in === compares objects by reference, so two arrays with the same content are not equal. A deep comparison walks both structures and compares the content. The design choices matter, and an interviewer will usually ask which ones were made.

Steps for a solid version:

  1. If Object.is(a, b), return true. This handles identical references and makes NaN equal to NaN. Decide whether 0 and -0 should be equal. Object.is says they differ; many libraries treat them as equal.
  2. If either value is not an object (or is null), return false, since the primitives were already compared.
  3. Compare the prototypes or Object.prototype.toString tags, so an array does not equal an object with the same keys, and a Date does not equal a plain object.
  4. For Date, compare getTime(). For RegExp, compare source and flags.
  5. For Map and Set, compare size, then entries. Map keys that are objects need a deep search, which is slower; a simple version checks keys by reference.
  6. For arrays and plain objects, compare the key lists (own keys, including symbols if needed) and then each value recursively. Key order should not matter for objects.
  7. Track visited pairs in a WeakMap so circular structures finish: if the pair (a, b) is already being compared, assume it is equal.

Decide what to do with functions (compare by reference), class instances (same prototype, then own properties), and non-enumerable properties (usually ignored). Time cost is proportional to the size of the data, and deep recursion can overflow on very deep structures.

For production code, use a tested library or node:util's isDeepStrictEqual, and write the version yourself in the interview.

javascript
function deepEqual(a, b, seen = new WeakMap()) {
  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 (seen.get(a) === b) return true; // already comparing this pair: assume equal
  seen.set(a, b);

  if (a instanceof Date) return a.getTime() === b.getTime();
  if (a instanceof RegExp) return a.source === b.source && a.flags === b.flags;

  if (a instanceof Map) {
    if (a.size !== b.size) return false;
    for (const [key, value] of a) {
      if (!b.has(key) || !deepEqual(value, b.get(key), seen)) return false;
    }
    return true;
  }
  if (a instanceof Set) {
    if (a.size !== b.size) return false;
    for (const value of a) if (!b.has(value)) return false;
    return true;
  }

  const keysA = Reflect.ownKeys(a);
  const keysB = Reflect.ownKeys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key], seen));
}

const checks = [
  ['same content, different key order', { a: 1, b: [1, 2, { c: 3 }] }, { b: [1, 2, { c: 3 }], a: 1 }, true],
  ['extra key', { a: 1 }, { a: 1, b: undefined }, false],
  ['NaN values', { n: NaN }, { n: NaN }, true],
  ['array versus object', [1, 2], { 0: 1, 1: 2, length: 2 }, false],
  ['dates', new Date('2026-01-01T00:00:00Z'), new Date('2026-01-01T00:00:00Z'), true],
  ['different dates', new Date(0), new Date(1), false],
  ['regexps', /ab+/gi, /ab+/gi, true],
  ['maps', new Map([['k', { v: 1 }]]), new Map([['k', { v: 1 }]]), true],
  ['sets', new Set([1, 2]), new Set([2, 1]), true],
  ['null versus object', null, {}, false],
  ['array order matters', [1, 2], [2, 1], false],
  ['zero and negative zero', 0, -0, false],
];
const nodeUtil = require('node:util');
for (const [label, x, y, expected] of checks) {
  const mine = deepEqual(x, y);
  console.log(label.padEnd(34), mine === expected ? 'ok' : 'WRONG', mine, '| node:util says', nodeUtil.isDeepStrictEqual(x, y));
}

const first = { name: 'loop', child: { items: [1, 2] } };
first.child.parent = first;
const second = { name: 'loop', child: { items: [1, 2] } };
second.child.parent = second;
console.log('circular structures:', deepEqual(first, second));
second.child.items.push(3);
console.log('after a change:', deepEqual(first, second));

Run with Node.js v24.22.1 as js-86.js; two runs gave identical output. Output: same content, different key order ok true | node:util says true extra key ok false | node:util says false NaN values ok true | node:util says true array versus object ok false | node:util says false dates ok true | node:util says true different dates ok false | node:util says false regexps ok true | node:util says true maps ok true | node:util says true sets ok true | node:util says true null versus object ok false | node:util says false array order matters ok false | node:util says false zero and negative zero ok false | node:util says false circular structures: true after a change: false

Key points

  • Start with Object.is for identical references and NaN.
  • Compare types or prototypes so arrays, objects, and dates do not mix.
  • Handle Date, RegExp, Map, and Set explicitly; compare arrays and objects by keys and values.
  • Key order should not matter for objects.
  • Track visited pairs in a WeakMap to survive circular references.

Common mistakes

  • Comparing JSON.stringify output, which depends on key order and drops undefined and functions.
  • Forgetting circular references and overflowing the stack.
  • Treating arrays and array-like objects with the same keys as equal.
  • Using == or loose comparison for primitives.

Follow-ups

  • How would you compare two Maps whose keys are objects?
  • How would you compare class instances with private fields?
  • What are the performance risks of deepEqual in a UI render loop?

Tips

  • Say the design choices out loud: NaN, negative zero, key order, and prototypes.
  • Add the WeakMap for cycles after the main version is working.
  • Mention isDeepStrictEqual or a library for production use.