Equality and immutability
Overview
Equality in JavaScript depends on the kind of value.
Primitives (numbers, strings, booleans…) are equal when their values are equal:
'js' === 'js'; // trueObjects and arrays are equal only when they are the same object:
{ a: 1 } === { a: 1 }; // false — two different objects
const x = { a: 1 };
const y = x;
x === y; // true — same objectThis is called reference equality (or identity): === asks “are these the same object in memory?”, not “do they look alike?”. It explains many puzzles from earlier topics — why includes can’t find an object by its contents, why two empty arrays aren’t equal, and why a Map key must be the exact object you stored.
The four ways to compare
| Comparison | Converts types? | NaN equals NaN? |
0 equals -0? |
|---|---|---|---|
== |
yes | no | yes |
=== |
no | no | yes |
Object.is |
no | yes | no |
SameValueZero (includes, Map, Set) |
no | yes | yes |
In practice: use === everywhere. Reach for Object.is only when NaN or -0 matter, such as in a generic comparison helper. Note that [NaN].includes(NaN) is true while [NaN].indexOf(NaN) is -1 — they use different rules.
Object.is
Object.is matches === except for two edge cases:
NaN === NaN; // false
Object.is(NaN, NaN); // true
Object.is(0, -0); // falseComparing by content
To compare objects by content, compare their properties yourself, or use a library for deep comparison.
For flat objects, compare each key (as in this topic’s exercise). For arrays of primitives:
const sameList = (a, b) => a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
sameList([1, 2, 3], [1, 2, 3]); // trueNested data needs a recursive comparison. You’ll often see this shortcut:
JSON.stringify(a) === JSON.stringify(b);It works for simple data, but fails if keys are in a different order ({a:1,b:2} vs {b:2,a:1}), and it ignores undefined and functions. Libraries like Lodash (isEqual) handle the edge cases properly.
Immutability
Data that can’t change is easier to reason about: nothing can alter it behind your back.
Imagine passing a settings object to a function that, deep inside, changes one property. Every other part of your program holding that object now sees the change — a bug that’s very hard to trace. If data is never changed, only replaced, that can’t happen.
const config = Object.freeze({ level: 'Beginner', tags: ['web'] });
config.level = 'Advanced'; // ignored (TypeError in strict mode)
config.tags.push('js'); // works — freeze is shallow!Levels of locking
| Method | Add properties | Remove properties | Change values |
|---|---|---|---|
Object.preventExtensions |
✗ | ✓ | ✓ |
Object.seal |
✗ | ✗ | ✓ |
Object.freeze |
✗ | ✗ | ✗ |
Check with Object.isFrozen(obj) and Object.isSealed(obj). All three are shallow: nested objects stay changeable unless you freeze them too (the deepFreeze in this topic’s exercise does exactly that).
Updating without changing
Instead of editing data, create a new version:
const next = { ...config, level: 'Advanced' };
const moreTags = [...config.tags, 'js'];
const withoutFirst = config.tags.slice(1);Arrays have dedicated non-mutating methods:
const scores = [30, 10, 20];
scores.toSorted(); // [10, 20, 30] — scores unchanged
scores.toReversed(); // [20, 10, 30]
scores.with(0, 99); // [99, 10, 20]
scores.toSpliced(1, 1); // [30, 20]For nested updates, copy each level along the path to the change:
const state = { user: { name: 'Asha', prefs: { theme: 'light' } } };
const nextState = {
...state,
user: {
...state.user,
prefs: { ...state.user.prefs, theme: 'dark' },
},
};
state.user.prefs.theme; // 'light' — untouched
nextState.user.prefs.theme; // 'dark'
nextState.user === state.user; // false — a new object on the changed pathWhy this pairs with identity equality
Here’s the payoff. If data is never changed in place, then “has anything changed?” becomes a cheap identity check: if nextState.user === state.user, nothing inside the user can have changed. Frameworks like React rely on exactly this to decide what to redraw — fast, without deep comparisons.
Remember
constisn’t immutability. It only stops the variable being reassigned; the object it points to can still change.
In summary
- Compare primitives with
===; compare objects by content only when you mean to, with a helper. - Prefer creating new objects and arrays over changing existing ones, especially for data shared across your program.
- Freeze configuration and constants that should never change.
Compare by value
Write sameSettings(a, b) that returns true when two flat objects have the same keys and values. Then write deepFreeze(obj) that freezes an object and every object nested inside it.
function sameSettings(a, b) {
// your code here
}
function deepFreeze(obj) {
// your code here
}function sameSettings(a, b) {
const keysA = Object.keys(a);
const keysB = Object.keys(b);
return keysA.length === keysB.length && keysA.every((k) => Object.is(a[k], b[k]));
}
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value && typeof value === 'object') deepFreeze(value);
}
return Object.freeze(obj);
}Summary
- Primitives compare by value; objects compare by identity (are they the same object?).
- Use
===;Object.isis the same exceptNaNequals itself and0differs from-0. - Compare objects by content yourself — key by key, or deeply for nested data.
Object.freezestops changes to an object’s top level; it’s shallow.- Update immutably by creating new objects and arrays instead of editing old ones.