Sub topic 11
Comparing Objects and Arrays by Reference
This chapter assumes you know how === and == treat primitives, as covered in the earlier chapters on strict and loose equality. It also assumes you are comfortable with object and array literals and can run code in Node.js or a browser console.
Primitives such as numbers and strings are compared by value: 3 === 3 is true because both sides hold the same number. Objects work differently. Arrays, functions, dates, and plain objects are all objects. A variable holding an object stores a reference, which is a pointer to one particular object in memory. The equality operators compare those references and ignore what the objects contain.
The core rule: identity, not content
When both operands are objects, ===, ==, and Object.is all ask the same question: are these the same object? Two objects with identical properties are still two separate objects.
const a = { x: 1 };
const b = { x: 1 };
const c = a;
console.log(a === b); // false: two distinct objects
console.log(a === c); // true: c holds the same reference as a
console.log(a == b); // false: == does not compare contents either
console.log(Object.is(a, c)); // true
console.log([1, 2] === [1, 2]); // false: each literal creates a new array
console.log({} === {}); // falseEach object literal { ... } and array literal [ ... ] creates a new object every time it is evaluated. That is why [] === [] is false, even though both arrays are empty.
Shared references and mutation
Assigning an object to a new variable copies the reference, not the object. Both names then point at one object, so a change made through one name shows up through the other.
const original = { count: 0 };
const alias = original;
alias.count = 5;
console.log(original.count); // 5
console.log(original === alias); // true
const copy = { ...original }; // a shallow copy: a new object
console.log(copy === original); // false
copy.count = 10;
console.log(original.count); // 5: original is unaffectedSpread ({ ...obj }, [...arr]) makes a shallow copy: the outer object is new, but nested objects are still shared.
const settings = { theme: { dark: true } };
const clone = { ...settings };
console.log(clone === settings); // false
console.log(clone.theme === settings.theme); // true: the nested object is sharedWhen == converts an object
There is one case where an object's contents affect equality. If == compares an object with a primitive, it first converts the object with ToPrimitive. For arrays this usually means calling toString(), which joins the elements with commas.
console.log([1, 2] == '1,2'); // true: [1, 2] becomes '1,2'
console.log([0] == 0); // true: [0] -> '0' -> 0
console.log({} == '[object Object]'); // true
console.log([1, 2] == [1, 2]); // false: two objects, so no conversion happensThis matches a string by accident and does not compare contents. It is one more reason to use ===.
Wrapper objects follow the same rules. new String('a') is an object, not a primitive string:
const s1 = new String('a');
const s2 = new String('a');
console.log(s1 === 'a'); // false: object vs primitive
console.log(s1 == 'a'); // true: s1 is converted to 'a'
console.log(s1 == s2); // false: two different objectsIdentity in built-in methods and collections
Methods that search for values use identity for objects too. That includes indexOf, includes, Set, and Map keys.
const item = { id: 1 };
const list = [item, { id: 2 }];
console.log(list.includes(item)); // true: same reference
console.log(list.includes({ id: 1 })); // false: a new object
console.log(list.findIndex((o) => o.id === 1)); // 0: compare a field instead
const seen = new Set();
seen.add({ id: 1 });
seen.add({ id: 1 });
console.log(seen.size); // 2: the Set holds two distinct objects
const cache = new Map();
const key = ['a'];
cache.set(key, 'value');
console.log(cache.get(key)); // 'value'
console.log(cache.get(['a'])); // undefinedTo search by content, use find, findIndex, or some with a predicate that compares the fields you care about. To use content as a Map key, derive a primitive key such as an ID string.
Comparing by content
No operator compares contents, so you choose a strategy. Each one has trade-offs.
| Approach | Good for | Pitfalls |
|---|---|---|
| Compare a unique field (`a.id === b.id`) | Entities with IDs | Ignores the other fields |
| Shallow compare of own keys | Flat objects, React-style props | Nested objects compared by reference |
| `JSON.stringify(a) === JSON.stringify(b)` | Quick checks on plain data | Key order matters; `undefined` dropped; `NaN` becomes `null`; dates become strings; fails on cycles and BigInt |
| Recursive deep equality | Nested plain data | Must decide how to treat dates, maps, prototypes, cycles |
| `util.isDeepStrictEqual` (Node.js) | Server code and tests | Not available in browsers |
The JSON.stringify pitfalls show up quickly:
console.log(JSON.stringify({ a: 1, b: 2 }) === JSON.stringify({ b: 2, a: 1 })); // false: key order
console.log(JSON.stringify({ a: undefined }) === JSON.stringify({})); // true: undefined dropped
console.log(JSON.stringify([NaN]) === JSON.stringify([null])); // true: NaN becomes nullA deep equality function
Here is a recursive version for plain objects, arrays, and dates. It uses Object.is for primitives, so NaN equals NaN and 0 does not equal -0.
function deepEqual(a, b) {
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 (a instanceof Date) return Object.is(a.getTime(), b.getTime());
const keysA = Object.keys(a);
const keysB = Object.keys(b);
if (keysA.length !== keysB.length) return false;
for (const key of keysA) {
if (!Object.hasOwn(b, key) || !deepEqual(a[key], b[key])) return false;
}
return true;
}
console.log(deepEqual({ a: [1, { b: 2 }] }, { a: [1, { b: 2 }] })); // true
console.log(deepEqual([1, 2], { 0: 1, 1: 2 })); // false: different prototypes
console.log(deepEqual(new Date(0), new Date(0))); // true
console.log(deepEqual(new Date(0), new Date(1))); // false
console.log(deepEqual({ x: NaN }, { x: NaN })); // trueThe Date check matters. Dates have no own enumerable keys, so without it any two dates would compare as equal. Map and Set have the same problem, and this function does not handle them or circular references. A library such as Lodash's isEqual covers those cases.
Common mistakes
- Writing
if (arr === [])to test for an empty array. It is always false. Usearr.length === 0. - Writing
if (obj == {})to test for an empty object. It is always false. UseObject.keys(obj).length === 0. - Expecting
list.includes({ ... })orset.has({ ... })to find an object built from a fresh literal. - Treating a spread copy as fully independent when it contains nested objects. Use
structuredClone(obj)for a deep copy of cloneable data.
Exercise
What do these lines log, and why? const p = [1]; const q = p; const r = [...p]; console.log(p === q, p === r, p == '1', r[0] === p[0]);
Show answer
true false true true. q holds the same reference as p. r is a new array, so p === r is false. p == '1' converts [1] to the string '1'. r[0] and p[0] are both the primitive 1, which is compared by value.
Exercise
A Set of user objects grows every time the same user logs in, because users.add({ id: 7, name: 'Ana' }) is called each time. How do you fix it?
Show answer
Each literal is a new object, so the Set treats it as a new member. Use a primitive key instead: keep a Map keyed by user.id (users.set(user.id, user)), or a Set of IDs. Equal primitive keys are then detected by value.
Exercise
Why does JSON.stringify(a) === JSON.stringify(b) report { a: 1, b: 2 } and { b: 2, a: 1 } as different, and why might the deepEqual function above wrongly report two different Map objects as equal?
Show answer
JSON.stringify writes keys in insertion order, so the two strings differ even though the contents match. A Map keeps its entries internally and has no own enumerable keys. Object.keys returns [] for both maps, the prototypes match, and the function returns true. Comparing maps correctly needs a separate check that walks their entries.