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

Comparing Object Keys and Values

Using Object.keys to compare key sets, then recursively comparing the value at each key.

Comparing Object Keys and Values

You'll learn how to systematically compare two objects by checking their keys first, then recursively comparing each value.

The Core Idea

When building a deep equality checker, you've already handled primitives and arrays—now it's time for objects. Comparing objects properly means two things: first, do both objects have the same set of keys? Second, are the values at each key deeply equal? We use Object.keys() to extract key sets, compare them, and then recurse through each key-value pair.

How It Works

Start by getting both objects' keys with Object.keys(obj1) and Object.keys(obj2). If the lengths differ, the objects can't be equal. If lengths match, check that every key from obj1 exists in obj2 (and vice versa if you want to be thorough). Finally, loop through each key and recursively compare the values:

function deepEqual(a, b) {
  // ... (primitives, arrays handled earlier)
  
  // Both are objects at this point
  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)) return false;
    if (!deepEqual(a[key], b[key])) return false;
  }
  
  return true;
}

Analogy: Think of it like comparing two filing cabinets. First, check both have the same drawer labels. Then, open each matching drawer and compare its contents (which might themselves be nested filing cabinets).

Why This Order Matters

Keys first, values second. This is efficient—if key sets don't match, you bail out early without expensive recursive comparisons. The recursion handles nested objects naturally.

Key Takeaway: Deep object comparison requires checking key equality with Object.keys(), then recursively comparing the value at each matching key—a two-phase pattern that scales to any depth.