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

Why Deep Equality Is Needed

Understanding when shallow equality (===) fails for objects and arrays, and why deep comparison is necessary.

Why Deep Equality Is Needed

You'll learn why comparing objects and arrays with === doesn't work as you might expect, and when you need deep equality checks instead.

The Problem with Shallow Equality

In JavaScript, the === operator performs shallow equality — it checks if two values occupy the same location in memory. For primitives (numbers, strings, booleans), this works perfectly. But for objects and arrays, === only returns true if both variables reference the exact same object in memory:

const obj1 = { name: 'Alice', age: 30 };
const obj2 = { name: 'Alice', age: 30 };

console.log(obj1 === obj2); // false — different objects in memory
console.log(obj1 === obj1); // true — same reference

Even though obj1 and obj2 have identical contents, they're stored at different memory addresses, so === sees them as different.

When You Need Deep Equality

Deep equality compares the contents of objects recursively, not just their references. You need this when:

  • Comparing state before/after changes in React or Redux
  • Validating form data against saved values
  • Testing if two API responses are equivalent
  • Detecting changes in configuration objects
  • Checking if nested data structures match
const user1 = { name: 'Bob', address: { city: 'NYC' } };
const user2 = { name: 'Bob', address: { city: 'NYC' } };

// Shallow equality fails
console.log(user1 === user2); // false
console.log(user1.address === user2.address); // false

// Deep equality would return true by comparing contents

Key Takeaway: Use === for primitives and reference identity checks, but implement or use a library's deep equality function when you need to compare object contents recursively — because === only checks if two variables point to the same object in memory.