Skip to content

deepEqual

Saurav-TB-Pandey edited this page Aug 10, 2026 · 2 revisions

deepEqual

A highly optimized utility function that deeply compares two values for structural equality. It handles complex nesting, circular references without crashing, and accurately compares native JavaScript objects like Date, RegExp, Map, and Set.

Usage Examples

Basic

Comparing complex, deeply nested objects.

import { deepEqual } from "react-hook-lab";

const objA = { user: { name: "Alice", active: true } };
const objB = { user: { name: "Alice", active: true } };

console.log(objA === objB); // false (different memory references)
console.log(deepEqual(objA, objB)); // true (structurally identical!)

Common

Comparing advanced JavaScript data types.

import { deepEqual } from "react-hook-lab";

const dateA = new Date("2024-01-01");
const dateB = new Date("2024-01-01");
console.log(deepEqual(dateA, dateB)); // true

const regexA = /hello/ig;
const regexB = /hello/ig;
console.log(deepEqual(regexA, regexB)); // true

const mapA = new Map([['key', { val: 1 }]]);
const mapB = new Map([['key', { val: 1 }]]);
console.log(deepEqual(mapA, mapB)); // true

API Reference

Parameters

  • a (any): The first value to compare.
  • b (any): The second value to compare.

Return Type

Returns a strict boolean. true if the values are structurally equal, false otherwise.

Core Working

  1. Fast-path Reference Check: It immediately returns true if Object.is(a, b) matches.
  2. Circular Reference Handling: It uses an internal WeakMap to track objects it has already visited. If it encounters a self-referential loop, it correctly resolves the equality instead of throwing a Maximum Call Stack Size Exceeded error.
  3. Type-Specific Checks: It leverages instance checks (instanceof) to apply specialized, high-performance comparisons for Array, Date, RegExp, Map, and Set.
  4. Object Key Iteration: For plain objects, it checks if both objects have the exact same number of keys, and then recursively checks deepEqual on every key-value pair.

Clone this wiki locally