How to Compare Two Objects Deeply in JavaScript Correctly
Compare objects by content with isDeepStrictEqual or a recursive function that handles key order, NaN, dates, maps and cycles. See why JSON.stringify fails.

Two objects with the same fields are different objects, and { a: 1 } === { a: 1 } is false. Everyone learns this early, and then meets the harder question: what should "the same" mean for objects that hold other objects, arrays, dates, maps and values such as NaN? A deep comparison walks both structures together and compares leaves, and each decision it makes is a policy: does key order matter, is undefined the same as a missing key, are two class instances equal to a plain object with the same fields, what happens with a circular reference. This post shows a correct deep comparison from scratch with tests for each decision, the built-in one in Node.js, why the one-line JSON.stringify shortcut gives wrong answers, a function that reports where two objects differ, and the mistakes we have made, one of which caused an infinite render loop. The examples run on Node.js 24.
Shallow comparison first
Many comparisons only need one level, and the check is short.
const shallowEqual = (a, b) => {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every((key) => Object.hasOwn(b, key) && Object.is(a[key], b[key]));
};
const address = { city: "London" };
console.log(shallowEqual({ id: 1, address }, { id: 1, address }));
console.log(shallowEqual({ id: 1, address }, { id: 1, address: { city: "London" } }));
console.log(shallowEqual({ id: 1 }, { id: 1, extra: undefined }));
console.log(shallowEqual({ a: 1, b: 2 }, { b: 2, a: 1 }));true
false
false
trueThe function compares own keys and their values by identity. It is true when the nested object is the very same object, and false when it is an equal copy, which is the point of the next section. The third line shows the policy about undefined: a missing key and a key holding undefined are different, because the key lists differ. Key order does not matter, as the last line shows.
A deep comparison from scratch
function deepEqual(a, b, seen = new WeakMap()) {
if (Object.is(a, b)) return true;
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false;
if (seen.get(a) === b) return true;
seen.set(a, b);
if (a instanceof Date) return a.getTime() === b.getTime();
if (a instanceof RegExp) return String(a) === String(b);
if (a instanceof Map) {
if (a.size !== b.size) return false;
for (const [key, value] of a) {
if (!b.has(key) || !deepEqual(value, b.get(key), seen)) return false;
}
return true;
}
if (a instanceof Set) {
if (a.size !== b.size) return false;
for (const value of a) if (!b.has(value)) return false;
return true;
}
const keysA = Reflect.ownKeys(a);
const keysB = Reflect.ownKeys(b);
if (keysA.length !== keysB.length) return false;
return keysA.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key], seen));
}
console.log(deepEqual({ a: 1, b: { c: [1, 2] } }, { b: { c: [1, 2] }, a: 1 }));
console.log(deepEqual({ a: 1 }, { a: 1, b: undefined }));
console.log(deepEqual({ a: NaN }, { a: NaN }));
console.log(deepEqual({ a: [1, 2] }, { a: [1, 3] }));true
false
true
falseThe function first accepts values that are identical by Object.is, which covers primitives and NaN, and rejects any pair where one side is not an object. Objects with different prototypes are different. The seen map records pairs that are being compared, which is what makes circular structures safe. Dates and regular expressions are compared by value, maps and sets by size and entries, and everything else by its own keys, including symbol keys through Reflect.ownKeys. Arrays are handled by the same last branch, since their indexes and length are own keys. The policy choices, which the tests above pin down, are that key order is ignored, a missing key differs from undefined, and NaN equals NaN.
More cases, one policy each
class Point {
constructor(x) {
this.x = x;
}
}
console.log(deepEqual(new Point(1), new Point(1)), deepEqual(new Point(1), { x: 1 }));
console.log(deepEqual(new Date(0), new Date(0)), deepEqual(new Date(0), new Date(1)));
console.log(deepEqual([1, 2], { 0: 1, 1: 2, length: 2 }));
console.log(deepEqual(new Map([["k", { n: 1 }]]), new Map([["k", { n: 1 }]])));
console.log(deepEqual(new Set([1, 2]), new Set([2, 1])), deepEqual(/a/g, /a/i));
console.log(deepEqual(null, null), deepEqual(null, {}), deepEqual(0, -0));true false
true false
false
true
true false
true false falseTwo instances of the same class are equal, and an instance is not equal to a plain object with the same fields, because the prototypes differ. An array is not equal to an array-like object for the same reason. Maps compare their values deeply and sets compare their members by identity, so a set of objects is only equal when it holds the same object references. The last line shows 0 and -0 as different, since Object.is distinguishes them: change the first line of the function to a === b || Object.is(a, b) if you want them equal.
Circular references
const x = { name: "x", list: [1, 2] };
x.self = x;
const y = { name: "x", list: [1, 2] };
y.self = y;
console.log(deepEqual(x, y));
const z = { name: "x", list: [1, 2] };
z.self = { name: "other", list: [], self: null };
console.log(deepEqual(x, z));true
falseWithout the seen map, the first call would recurse until the call stack overflowed with a RangeError, because x.self leads back to x. With it, the pair (x, y) is recorded on the way in, and the comparison of x.self with y.self finds the same pair and accepts it. The second comparison reaches a real difference and returns false. Cycles are common in data that came from an ORM, a DOM tree or a graph, and a comparison that does not handle them is a time bomb.
The built-in version in Node.js
import { isDeepStrictEqual } from "node:util";
console.log(isDeepStrictEqual({ a: 1, b: [1, { c: 2 }] }, { b: [1, { c: 2 }], a: 1 }));
console.log(isDeepStrictEqual({ a: 1 }, { a: "1" }));
console.log(isDeepStrictEqual({ a: NaN }, { a: NaN }));
console.log(isDeepStrictEqual(new Point(1), { x: 1 }));
console.log(isDeepStrictEqual(new Map([["k", 1]]), new Map([["k", 1]])));
console.log(isDeepStrictEqual(x, y));true
false
true
false
true
trueisDeepStrictEqual follows the same policies as the function above: strict equality at the leaves, so 1 and "1" differ, NaN equal to NaN, prototypes compared, and cycles handled. In Node.js, use it, and in tests use assert.deepStrictEqual(a, b), which throws an error with a readable diff. In browsers, a library such as Lodash with _.isEqual provides the same, and a hand-written function like the one above is fine when you control the data shapes. Do not use the legacy assert.deepEqual, which compares with == and treats 1 and "1" as equal.
Why JSON.stringify is the wrong shortcut
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
console.log(same({ a: 1, b: 2 }, { a: 1, b: 2 }));
console.log(same({ a: 1, b: 2 }, { b: 2, a: 1 }));
console.log(same({ a: 1, b: undefined }, { a: 1 }));
console.log(same({ when: new Date(0) }, { when: "1970-01-01T00:00:00.000Z" }));
console.log(same({ n: NaN }, { n: null }), same({ s: new Set([1]) }, { s: {} }));true
false
true
true
true trueEqual objects built with keys in a different order produce different text, so they compare as unequal. Objects that differ in a key holding undefined compare as equal. Dates equal their own string form. NaN equals null, and a set equals an empty object, because JSON turns the set into {}. The method fails in both directions, and it also throws for circular references and for BigInt. It is acceptable only for plain data that you know has stable key order and no special values, and a deep comparison function removes the need to know.
Reporting what differs
For a test message, a log line or a form, you want the path of each difference, and not just a yes or no.
function diff(a, b, path = "") {
const differences = [];
const keys = new Set([...Object.keys(a), ...Object.keys(b)]);
for (const key of keys) {
const here = path === "" ? key : `${path}.${key}`;
if (!Object.hasOwn(a, key) || !Object.hasOwn(b, key)) {
differences.push(here);
} else if (a[key] !== null && b[key] !== null && typeof a[key] === "object" && typeof b[key] === "object") {
differences.push(...diff(a[key], b[key], here));
} else if (!Object.is(a[key], b[key])) {
differences.push(here);
}
}
return differences;
}
console.log(diff({ a: 1, b: { c: 2, d: 3 } }, { a: 1, b: { c: 5 }, e: 1 }));
console.log(diff({ list: [1, 2, 3] }, { list: [1, 9, 3] }));
console.log(diff({ same: true }, { same: true }));[ 'b.c', 'b.d', 'e' ]
[ 'list.1' ]
[]The function lists the dotted path of each leaf that differs or exists on one side only. Arrays are walked like objects, so the changed element is reported as list.1. An empty list means the objects are equal under this policy. It is not a replacement for a complete diff library, since it does not report moved array items or type changes inside dates, and it is enough for an error message.
A mistake we hit: the infinite render loop
function hasChanged(previous, next) {
return JSON.stringify(previous) !== JSON.stringify(next);
}
const fromServer = { id: 1, name: "Ada", tags: ["a"] };
const fromCache = { name: "Ada", tags: ["a"], id: 1 };
console.log(hasChanged(fromServer, fromCache));
console.log(!deepEqual(fromServer, fromCache));true
falseA cache layer compared a fresh server response with the cached copy to decide whether to update, and the server returned the same fields in a different order on every other request. The JSON comparison said the data had changed, the update triggered another request, and the loop never settled: the page re-rendered until the browser tab was killed. A deep comparison that ignores key order says nothing changed, and the loop stopped. Comparing structured data by its text form means comparing how it was serialized, and not what it contains.
Choosing between the methods
| You want | Use |
|---|---|
| One level, nested objects by identity | A shallowEqual function |
| Full content comparison in Node.js | isDeepStrictEqual from node:util |
| A test assertion with a diff | assert.deepStrictEqual(a, b) |
| The same in a browser | _.isEqual from Lodash, or your own function |
| Where two objects differ | A diff helper that returns paths |
| Never | JSON.stringify(a) === JSON.stringify(b) |
Practical rules we follow
Decide the policies before writing the code: key order, undefined against missing, NaN, prototypes, symbols and cycles. Use isDeepStrictEqual in Node.js. Keep a seen map in any recursive comparison. Compare class instances by prototype. Use shallow comparison for change detection in hot paths, and deep comparison where correctness matters. Never compare serialized text. And test with key order swapped, a NaN, a date and a cycle.
Where deep comparison stops
Functions are compared by identity, so two objects holding different but equivalent functions are unequal. Getters are read, which can run code or throw. Non-enumerable properties are ignored by Object.keys and counted by Reflect.ownKeys, so the two disagree on hidden data. Very large structures take time proportional to their size, and shared structures may be compared more than once. And equality of mutable objects is a snapshot: the answer can change a moment later. The reference is in the Node.js util.isDeepStrictEqual documentation and the Node.js assert module documentation.


