Handling Primitive vs Reference Types
What you'll learn: How to distinguish between primitives that can use === and objects that require recursion when implementing deep equality checks.
The Core Challenge
When building a deep equality function, the first critical step is determining what kind of value you're comparing. JavaScript has two fundamental categories:
Primitives (number, string, boolean, null, undefined, symbol, bigint) are compared by value. The strict equality operator === works perfectly here—if two primitives hold the same value, they're equal.
Reference types (objects, arrays, dates, etc.) are compared by reference with ===. Two objects with identical properties will fail a === check if they're separate instances. This is where deep equality requires recursion.
Why This Matters
function deepEqual(a, b) {
// Primitives: === works perfectly
if (a === b) return true;
// Now we know they're not === equal
// Are they both objects? (reference types)
if (typeof a !== 'object' || typeof b !== 'object') {
return false; // One is primitive, other isn't
}
// Both are objects - need recursion
// (implementation continues...)
}
The pattern checks === first as an optimization—primitives and same-reference objects exit immediately. Only when that fails and both values are objects do you recurse.
Think of it like sorting mail: letters (primitives) can be compared at a glance, but packages (objects) need to be opened and contents examined one by one.
The typeof Gotcha
Remember: typeof null === 'object' (JavaScript quirk), so you must explicitly handle null before checking object properties.
Key Takeaway: Deep equality algorithms branch on type—primitives use === for instant comparison, while reference types require recursive property-by-property checking.