JavaScript

Deep Equal Comparison

by @admin
10h ago
Apr 28, 2026
Public
Performs a recursive structural equality check between two values. Handles primitives, arrays, objects, Dates, Maps, Sets, null, and undefined. Faster than JSON.stringify comparison (which ignores undefined and Map/Set), and avoids the false-positive trap of == or Object.is for nested structures.
JavaScript
function deepEqual(a, b) {
  if (a === b) return true;
  if (a == null || b == null) return a === b;
  if (typeof a !== typeof b) return false;

  if (a instanceof Date) return a.getTime() === b.getTime();
  if (a instanceof Set)  return a.size === b.size && [...a].every((v) => b.has(v));
  if (a instanceof Map) {
    if (a.size !== b.size) return false;
    for (const [k, v] of a) { if (!deepEqual(v, b.get(k))) return false; }
    return true;
  }
  if (typeof a !== 'object') return false;

  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every((k) => deepEqual(a[k], b[k]));
}

// Usage
console.log(deepEqual({ a: [1, 2] }, { a: [1, 2] })); // true
console.log(deepEqual({ a: 1 }, { a: 2 }));            // false
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.