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

Edge Cases: Null, Undefined, and NaN

Handling special values like null (typeof 'object'), undefined, and NaN (which !== itself) in deep equality.

Edge Cases: Null, Undefined, and NaN

You'll learn how to correctly handle JavaScript's quirky special values when implementing deep equality checks.

The Challenge

When building a deep equality function, three values demand special attention: null, undefined, and NaN. Each behaves unexpectedly in comparisons and can break naive implementations.

Why These Values Are Tricky

Null's typeof lie: Despite being a primitive, typeof null returns "object". This can cause your deep equality function to treat null as an object and attempt recursive comparison, leading to errors.

Undefined's subtle differences: While undefined === undefined works, you need to decide whether null and undefined should be considered equal in your deep comparison (usually they shouldn't be).

NaN's unique inequality: NaN is the only JavaScript value that doesn't equal itself (NaN !== NaN). A simple === check will incorrectly report two NaN values as unequal, even though they're conceptually the same special value.

Handling These Cases

function deepEqual(a, b) {
  // Handle NaN (must check before ===)
  if (Number.isNaN(a) && Number.isNaN(b)) return true;
  
  // Strict equality catches most primitives
  if (a === b) return true;
  
  // Null is typeof "object" but not an object
  if (a === null || b === null) return false;
  
  // Undefined explicit check
  if (a === undefined || b === undefined) return false;
  
  // Now safe to check typeof and recurse...
  // (rest of your deep equality logic)
}

The order matters: check NaN first, then use ===, then explicitly guard against null and undefined before treating values as objects.

Key Takeaway: Always handle null, undefined, and NaN explicitly at the start of your deep equality function—they break standard comparison rules and typeof assumptions.