Course contentsShow
← JavaScript
Lesson 2406 of 2,72349. Common Patterns and IdiomsFree lesson

Recursive Deep Equality Algorithm

Building a basic recursive function to compare nested objects and arrays element-by-element.

Recursive Deep Equality Algorithm

You'll learn how to build a recursive function that compares two values deeply, checking if nested objects and arrays are structurally identical element-by-element.

Why Recursive Equality?

When you need to compare complex nested structures, JavaScript's === operator only checks reference identity for objects—not their contents. You need a function that dives into every level of nesting and compares values directly.

The Core Algorithm

A recursive deep equality function follows this pattern:

  1. Base cases first: If both values are primitives or identical references, compare with ===
  2. Type mismatch: If types differ, return false
  3. Null check: Handle null explicitly (since typeof null === "object")
  4. Array handling: Check if both are arrays, compare lengths, then recurse on each element
  5. Object handling: Compare key counts, ensure all keys match, then recurse on each property value
function deepEqual(a, b) {
  // Same reference or primitive equality
  if (a === b) return true;
  
  // Type or null mismatch
  if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) {
    return false;
  }
  
  // Array comparison
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    for (let i = 0; i < a.length; i++) {
      if (!deepEqual(a[i], b[i])) return false;
    }
    return true;
  }
  
  // Object comparison
  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  
  for (let key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) {
      return false;
    }
  }
  
  return true;
}

Key Takeaway: A recursive deep equality function compares nested structures by handling base cases first, then recursively comparing each element or property until it confirms every level matches or finds a difference.