Hiprup

What is the difference between deep and shallow equality?

How thoroughly two values are compared.

  • Shallow — compares top-level values/references only; nested objects must be the same reference.

  • Deep — recursively compares every level, so structurally identical objects are equal.

Note: no built-in deep-equal — use Lodash isEqual or a recursive function.

// Shallow equality (top-level only)
function shallowEqual(a, b) {
  if (a === b) return true;
  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every(k => a[k] === b[k]);
}

const x = { a: 1, b: { c: 2 } };
const y = { a: 1, b: { c: 2 } };
console.log(shallowEqual(x, y)); // false (b objects are different references)

// Deep equality
function deepEqual(a, b) {
  if (a === b) return true;
  if (typeof a !== typeof b || a === null || b === null) return false;
  if (typeof a !== 'object') return false;
  const keysA = Object.keys(a), keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;
  return keysA.every(k => deepEqual(a[k], b[k]));
}

console.log(deepEqual(x, y)); // true (same content at all levels)

shallowEqual checks top-level values with === (nested objects fail because different references). deepEqual recursively checks all levels (nested objects with same content are equal). React uses shallow equality for memo/PureComponent — new objects cause re-renders even with identical content.

Implement both from scratch. Shallow: top-level ===. Deep: recursive comparison.

React uses shallow equality — explain why new objects in render defeat React.memo. JSON.stringify for quick deep comparison (but order-dependent and loses non-JSON types).

What is the difference between deep and shallow equality? | Hiprup