Skip to content
jshacks.dev
Fundamentals

How Equality Works for Objects and Arrays in JavaScript

Objects and arrays are equal only when they are the same object, whatever their contents. See shallow and deep checks, isDeepStrictEqual and why JSON fails.

9 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, npm and Node.js logos.

Two arrays with the same items are not equal, two objects with the same fields are not equal, and neither is a bug in the language. Equality for objects asks whether two names point at the same thing, and the contents do not enter into it. Programs nearly always want the other question, and the gap between the two is where includes, Set, Map keys, indexOf and test assertions fail in ways that look unreasonable. This post shows identity comparison, then three ways to compare contents with increasing cost: a shallow check, a hand-written deep check and the Node.js built-in. It runs on Node.js 24. The reference model underneath is in the post on primitives versus objects, and the comparison operators themselves are in the post on loose versus strict equality.

Identity is the default

Strict and loose equality both compare references when both operands are objects.

JavaScript
const a = { id: 1 };
const b = { id: 1 };
const alias = a;

console.log(a === b, a == b);
console.log(a === alias);
console.log([1, 2] === [1, 2]);
console.log(Object.is(a, alias), Object.is(a, b));

const list = [a];
console.log(list.includes(a), list.includes({ id: 1 }));
console.log(list.indexOf(b));
console.log(new Set([a, b, alias]).size);
console.log(new Map([[a, "first"]]).get({ id: 1 }));
Text
false false
true
false
true false
true false
-1
2
undefined

Two literals with identical contents are different objects. a and alias are one object under two names, so they are equal. Every identity-based API follows the same rule: includes(), indexOf(), Set and Map all failed to match the look-alike. A Set of three references held two objects, since alias is a. That is the consistent part, and the practical consequence is that objects make poor keys unless you hold on to the very object you stored.

A shallow comparison

A shallow check compares the top-level fields with ===. It is cheap, it is what React uses to decide whether props changed, and it is correct whenever the fields are primitives or references you reuse.

JavaScript
function shallowEqual(a, b) {
  if (Object.is(a, b)) return true;
  if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;

  const keysA = Object.keys(a);
  const keysB = Object.keys(b);
  if (keysA.length !== keysB.length) return false;

  return keysA.every((key) => Object.hasOwn(b, key) && Object.is(a[key], b[key]));
}

const shared = { city: "London" };

console.log(shallowEqual({ id: 1, name: "Ada" }, { name: "Ada", id: 1 }));
console.log(shallowEqual({ id: 1, address: shared }, { id: 1, address: shared }));
console.log(shallowEqual({ id: 1, address: { city: "London" } }, { id: 1, address: { city: "London" } }));
console.log(shallowEqual([1, 2], [1, 2]));
console.log(shallowEqual({ n: NaN }, { n: NaN }));
console.log(shallowEqual({ id: 1 }, { id: 1, extra: undefined }));
Text
true
true
false
true
true
false

Key order does not matter, and NaN compares equal because the helper uses Object.is. The third line shows the limit: two separate nested objects with equal contents are different at the second level. The last line shows a subtle point: a property set to undefined is not the same as a missing property, so the key counts differ. When fields are replaced and not mutated, the shallow check is exactly right, because an unchanged nested object keeps its identity.

A deep comparison written by hand

A recursive check handles nesting. A short version covers plain data, and writing it once shows what a full one has to handle.

JavaScript
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();

  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: 2 }] }, { a: [1, { b: 2 }] }));
console.log(deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 3 }] }));
console.log(deepEqual([1, 2], [1, 2, 3]));
console.log(deepEqual(new Date(0), new Date(0)));
console.log(deepEqual(new Map([[1, 2]]), new Map([[1, 3]])));

const loopA = { name: "x" };
loopA.self = loopA;
const loopB = { name: "x" };
loopB.self = loopB;
console.log(deepEqual(loopA, loopB));
Text
true
false
false
true
true
true

The function handles nesting, arrays, dates and cycles. It gets the Map case wrong, and the fifth line shows it: two maps with different contents printed true, because a Map keeps its entries internally and has no own enumerable keys to compare. That is the lesson: a hand-written deep equality is easy to start and hard to finish, with sets, maps, typed arrays, boxed primitives, getters and prototypes each needing a branch. For production use, take the built-in or a maintained library.

The built-in comparison in Node.js

util.isDeepStrictEqual() implements the same algorithm as assert.deepStrictEqual(), and it is available without installing anything.

JavaScript
import { isDeepStrictEqual } from "node:util";

const results = {
  "nested plain": isDeepStrictEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] }),
  "maps, same": isDeepStrictEqual(new Map([[1, { x: 1 }]]), new Map([[1, { x: 1 }]])),
  "maps, different": isDeepStrictEqual(new Map([[1, 2]]), new Map([[1, 3]])),
  "sets, other order": isDeepStrictEqual(new Set([1, 2]), new Set([2, 1])),
  "NaN": isDeepStrictEqual(NaN, NaN),
  "1 and '1'": isDeepStrictEqual([1], ["1"]),
  "0 and -0": isDeepStrictEqual(0, -0),
  "dates": isDeepStrictEqual(new Date(0), new Date(0)),
};

for (const [label, value] of Object.entries(results)) {
  console.log(label.padEnd(18), value);
}

class Point {
  constructor(x) {
    this.x = x;
  }
}

console.log(isDeepStrictEqual(new Point(1), { x: 1 }));
console.log(isDeepStrictEqual({ a: undefined }, {}));
Text
nested plain       true
maps, same         true
maps, different    false
sets, other order  true
NaN                true
1 and '1'          false
0 and -0           false
dates              true
false
false

Maps and sets compare by contents, with sets unordered. NaN equals itself. Strictness means no coercion, so [1] and ["1"] differ, and 0 and -0 differ as well, because the comparison follows Object.is. Prototypes count: a Point is not equal to a plain object with the same field. And a property that is undefined is not the same as a missing one. Pick the strict version for tests and data checks, since the loose isDeepEqual is legacy.

In tests, use the assertion that reports a diff.

JavaScript
import assert from "node:assert/strict";

try {
  assert.deepStrictEqual({ id: 1, tags: ["a"] }, { id: 1, tags: ["a", "b"] });
} catch (error) {
  console.log(error.code);
  console.log(error.message.split("\n")[0]);
}
Text
ERR_ASSERTION
Expected values to be strictly deep-equal:

The first line of the message says the values are not deeply equal, and the rest shows a diff of the two, which is what you want when a test fails.

The JSON shortcut and why it fails

Comparing JSON.stringify outputs is quick, and it breaks in predictable ways.

JavaScript
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: undefined }, {}));
console.log(same([NaN], [null]));
console.log(same(new Set([1]), new Set([2])));
console.log(same(new Date(0), "1970-01-01T00:00:00.000Z"));
Text
true
false
true
true
true
true

Key order changed the answer, which is wrong for objects. undefined and a missing key matched. NaN equaled null. Two different sets matched, because both serialize to {}. And a date matched the string it serializes to. The shortcut works for data you produced yourself, in a fixed key order and with plain types, and that is a narrow case.

Matching by key instead

When you need to find an object by what it contains, the usual answer is to identify it by a primitive field. A Map keyed by id, a Set of ids and a find() on a field all sidestep the question.

JavaScript
const users = [
  { id: 1, name: "Ada" },
  { id: 2, name: "Grace" },
];

const byId = new Map(users.map((u) => [u.id, u]));

console.log(byId.get(2).name);
console.log(users.some((u) => u.id === 1));
console.log(users.find((u) => u.id === 3));

const seen = new Set();
const unique = [{ id: 1 }, { id: 1 }, { id: 2 }].filter((item) => {
  if (seen.has(item.id)) return false;
  seen.add(item.id);
  return true;
});
console.log(unique);
Text
Grace
true
undefined
[ { id: 1 }, { id: 2 } ]

The lookup by id found the right user, and the deduplication kept one object per id. Choosing the identifying field is a modelling decision that no equality function can make for you, and it is almost always better than comparing whole objects.

Comparing copies

Equality questions often arise right after a copy, as in "is my clone the same as the original". The answer depends on the kind of copy, and the two ideas separate cleanly: a copy is never identical to its source, and a good copy is deeply equal to it.

JavaScript
import { isDeepStrictEqual } from "node:util";

const original = { id: 1, tags: ["a"], meta: { owner: "Ada" } };

const shallow = { ...original };
const deep = structuredClone(original);

console.log(shallow === original, deep === original);
console.log(isDeepStrictEqual(shallow, original), isDeepStrictEqual(deep, original));
console.log(shallow.tags === original.tags, deep.tags === original.tags);
Text
false false
true true
true false

Neither copy is the same object, both are deeply equal to the original, and only the shallow one shares its nested arrays. That is a useful property to assert in a test of a cloning function: deep equality shows the data survived, and identity on the nested parts shows how deep the copy went. The post on shallow and deep copies and the post on structuredClone() explain the copies themselves.

Choosing a comparison

Identity answers "is this the same object", and it is the right test for caches, change detection with immutable updates and Map keys that you control. A shallow check is the right test for props and state objects that follow immutable updates. A deep check is the right test for assertions and for comparing data from two sources. A key comparison is the right test for records with an identifier.

QuestionUse
Is it the same object=== or Object.is
Did any top-level field changeA shallow equal helper
Are two data structures the sameisDeepStrictEqual or assert.deepStrictEqual
Is this the same recordCompare an id

Equality in frameworks

Frameworks decide when to re-render by comparing, and knowing which comparison they use explains behavior that otherwise looks random. React compares props, state and hook dependencies with Object.is, one level deep for props through memo, so passing a new object literal on every render defeats memoization even when the contents are equal. Redux and similar stores compare by reference too, which is why reducers return new objects only for the parts that changed. If you find a component re-rendering for no visible reason, look for an object or array created inline in a parent: it is a new identity each time.

Where this advice stops

A deep comparison on large structures costs time in proportion to their size, and doing it on every render defeats the purpose of change detection. Compare identity first and fall through to a deep check only when identities differ. And equality of mutable objects is a snapshot: two objects equal now can diverge after the next edit, so do not cache a result of equality for objects you mutate.

The comparison rules are defined in the specification under IsStrictlyEqual and SameValue, and the Node.js documentation describes the built-in in util.isDeepStrictEqual.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.