Skip to content
jshacks.dev
Functions

Implement deepEqual From Scratch in JavaScript

Implement deepEqual from scratch in JavaScript for objects, arrays, dates, NaN, maps and sets, with cycle protection, and see how it differs from assert.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, TypeScript, npm, Node.js and Vite logos.

=== compares objects by identity, so two separate objects with identical contents are never equal. deepEqual(a, b) compares by structure instead: it returns true when the two values have the same shape and the same leaves. It is a favorite interview question because the naive version is easy and every refinement exposes a JavaScript quirk: NaN, -0, key order, arrays versus objects, dates, maps and sets, prototypes, and circular references. This post builds deepEqual in layers on Node.js 24, shows the output for each quirk and ends with how it compares to assert.deepStrictEqual. For the reverse problem, copying, see implementing deepClone.

Decide what equal means

Before writing code, state the rules, because there is no single correct answer. The version below treats two values as equal when they are the same primitive (with NaN equal to NaN), or both are objects with the same type, the same own keys and equal values at every key. It does not compare prototypes beyond the type, and it ignores non-enumerable properties. Saying that you made these choices is half the answer.

Version 1: primitives and plain objects

JavaScript
function deepEqualBasic(a, b) {
  if (a === b) {
    return true;
  }

  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) {
    return false;
  }

  const keysA = Object.keys(a);
  const keysB = Object.keys(b);

  if (keysA.length !== keysB.length) {
    return false;
  }

  return keysA.every((key) => Object.hasOwn(b, key) && deepEqualBasic(a[key], b[key]));
}

console.log(deepEqualBasic({ a: 1, b: { c: [1, 2] } }, { b: { c: [1, 2] }, a: 1 }));
console.log(deepEqualBasic({ a: 1 }, { a: 1, b: undefined }));
console.log(deepEqualBasic(1, "1"));
Text
true
false
false

The first check, a === b, handles equal primitives and the same object in one step. The second rejects anything that is not an object on both sides. Then the keys are compared by count and by presence in b, and each value is compared recursively. Key order does not matter, because the check goes through keysA and looks each key up in b. The second example shows a choice: { a: 1 } and { a: 1, b: undefined } differ, because the key counts are different. That matches assert.deepStrictEqual.

Object.hasOwn was added in ES2022 and is available in Node.js 16.9 and later. It is safer than key in b, which also looks at the prototype chain.

NaN and negative zero

JavaScript
console.log(deepEqualBasic(NaN, NaN));
console.log(deepEqualBasic(0, -0));
console.log(Object.is(NaN, NaN), Object.is(0, -0));
Text
false
true
true false

NaN === NaN is false, so the first check fails, and the next check rejects non-objects, so two NaN values are reported as different. For a test helper, that is the wrong answer, because a result of NaN compared with NaN should be equal. And 0 === -0 is true, so 0 and -0 are equal here, even though Object.is can tell them apart. Decide which you want. assert.deepStrictEqual uses Object.is for primitives, so it treats NaN as equal to NaN and 0 as different from -0. To match it, replace the first check with Object.is.

JavaScript
const sameValue = (a, b) => Object.is(a, b);

console.log(sameValue(NaN, NaN), sameValue(0, -0), sameValue(1, 1));
Text
true false true

Arrays versus objects

An array and an object with the same keys have the same Object.keys output, so Version 1 says they are equal.

JavaScript
console.log(deepEqualBasic([1, 2], { 0: 1, 1: 2 }));
Text
true

That is wrong for almost every use. Compare the kind of value before comparing the contents: both arrays or neither. A reliable way to compare types is the internal tag from Object.prototype.toString, which tells arrays, dates, regular expressions, maps and sets apart.

JavaScript
const tag = (value) => Object.prototype.toString.call(value);

console.log(tag([]), tag({}), tag(new Date(0)), tag(new Map()), tag(null));
Text
[object Array] [object Object] [object Date] [object Map] [object Null]

Version 2: built-in types and cycles

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;
  }

  const kind = Object.prototype.toString.call(a);

  if (kind !== Object.prototype.toString.call(b)) {
    return false;
  }

  if (seen.get(a) === b) {
    return true;
  }

  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;
    }

    return [...a].every(([key, value]) => b.has(key) && deepEqual(value, b.get(key), seen));
  }

  if (a instanceof Set) {
    if (a.size !== b.size) {
      return false;
    }

    return [...a].every((value) => b.has(value));
  }

  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));
}

console.log(deepEqual(NaN, NaN), deepEqual(0, -0));
console.log(deepEqual([1, 2], { 0: 1, 1: 2 }));
console.log(deepEqual(new Date(5), new Date(5)), deepEqual(new Date(5), new Date(6)));
console.log(deepEqual(new Map([["a", [1]]]), new Map([["a", [1]]])));
console.log(deepEqual(new Set([1, 2]), new Set([2, 1])));
Text
true false
false
true false
true
true

The kind check separates arrays from objects and dates from everything else. Dates are compared by their time value, regular expressions by source and flags, and maps by size and then by each key and value. For sets the code uses b.has(value), which compares by identity: a set of objects is equal only when it holds the same object references. A full structural comparison of set members is an O(n^2) problem, and it is fair to say so and leave it.

Reflect.ownKeys includes symbol keys, and on arrays it includes "length", which is compared like any other property.

Cycles

Two circular structures with the same shape should compare equal, and a naive recursion never finishes.

JavaScript
const x = { name: "x" };
x.self = x;

const y = { name: "x" };
y.self = y;

console.log(deepEqual(x, y));

const z = { name: "x" };
z.self = { name: "other" };

console.log(deepEqual(x, z));
Text
true
false

The seen map records pairs (a, b) that are currently being compared. When the recursion comes back to the pair (x, y), the code assumes it is equal and returns true, because any difference would be found by the other comparisons already in progress. This is the standard technique, and it is right as long as the map is keyed by the left side and the right side agrees. In the second comparison, x.self is x with two keys, and z.self is a separate object with one key, so the key counts differ and the result is false.

One subtle point: seen.get(a) === b handles one partner per object. If a is compared with two different partners within a call, only the latest is remembered. That is rare, and a pair set would be exact, at more cost.

Prototypes

Two objects with the same properties and different classes are equal here, because the tag for both is [object Object].

JavaScript
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

console.log(deepEqual(new Point(1, 2), { x: 1, y: 2 }));
console.log(Object.getPrototypeOf(new Point(1, 2)) === Object.getPrototypeOf({ x: 1, y: 2 }));
Text
true
false

If the prototype matters, add Object.getPrototypeOf(a) !== Object.getPrototypeOf(b) as a rejection after the tag check. That is what assert.deepStrictEqual does, and it is the stricter and usually safer choice. assert.deepEqual, the loose version, ignores prototypes and compares primitives with ==, which makes 1 equal to "1", so avoid it.

Comparing with the Node.js assert module

JavaScript
import assert from "node:assert/strict";

assert.deepStrictEqual({ a: [1, NaN] }, { a: [1, NaN] });

try {
  assert.deepStrictEqual({ a: 1 }, { a: "1" });
} catch (error) {
  console.log(error.code);
}
Text
ERR_ASSERTION

node:assert/strict is the right tool for tests, with readable diffs. Use your own deepEqual when you need a boolean in production code, for example to skip a state update when nothing changed, and keep in mind the cost: comparing two large structures walks both completely.

Performance and early exits

A structural comparison is linear in the size of the data when it succeeds, and it can stop early when it fails. Order the checks from cheapest to most expensive so that the common mismatch is found fast: identity first, then type, then key count, then the values. The key count check is especially useful, since it rejects most unequal objects without looking at any value.

For arrays, compare the lengths before the elements, and compare elements in order, stopping at the first difference. For very large structures that you compare repeatedly, consider whether you need deep equality at all. A version number or an updated-at field on the data, or immutable updates that give changed data a new identity, let you use === and skip the walk. That is the idea behind the shallow comparisons in UI libraries, which depend on code never mutating objects in place.

Finally, remember that deep equality is a question about values and not about behavior. Two functions with identical source are different values here, and two objects whose getters return the same data are only equal if the comparison reads the getters. Decide what your function does with those cases, document it, and keep the rule the same everywhere you use it.

Tests

JavaScript
import test from "node:test";

test("deepEqual follows the rules", () => {
  assert.equal(deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }), true);
  assert.equal(deepEqual({ a: 1 }, { a: 1, b: undefined }), false);
  assert.equal(deepEqual([], {}), false);
  assert.equal(deepEqual(NaN, NaN), true);
});
Text
ℹ tests 1
ℹ pass 1
ℹ fail 0
Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.