Equality and immutability

Topic 4 of 4 in Advanced concepts7 min readBeginnerFree course

Overview

Equality in JavaScript depends on the kind of value.

Primitives (numbers, strings, booleans…) are equal when their values are equal:

JavaScript
'js' === 'js'; // true

Objects and arrays are equal only when they are the same object:

JavaScript
{ a: 1 } === { a: 1 };   // false — two different objects
const x = { a: 1 };
const y = x;
x === y;                 // true — same object

Left: x points to an object and y = x points to the same one, so x === y is true. Right: p and q each point to their own object with the same contents, so p === q is false. Below, a table: NaN and NaN are not === but are Object.is; 0 and -0 are === but not Object.is; 1 and ‘1’ are only ==.

This 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:

JavaScript
NaN === NaN;          // false
Object.is(NaN, NaN);  // true
Object.is(0, -0);     // false

Comparing 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:

JavaScript
const sameList = (a, b) => a.length === b.length && a.every((v, i) => Object.is(v, b[i]));
sameList([1, 2, 3], [1, 2, 3]); // true

Nested data needs a recursive comparison. You’ll often see this shortcut:

JavaScript
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.

JavaScript
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:

JavaScript
const next = { ...config, level: 'Advanced' };
const moreTags = [...config.tags, 'js'];
const withoutFirst = config.tags.slice(1);

Arrays have dedicated non-mutating methods:

JavaScript
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:

JavaScript
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 path

Why 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 const isn’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.
Exercise

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.

JavaScript
function sameSettings(a, b) {
  // your code here
}

function deepFreeze(obj) {
  // your code here
}

Summary

  • Primitives compare by value; objects compare by identity (are they the same object?).
  • Use ===; Object.is is the same except NaN equals itself and 0 differs from -0.
  • Compare objects by content yourself — key by key, or deeply for nested data.
  • Object.freeze stops changes to an object’s top level; it’s shallow.
  • Update immutably by creating new objects and arrays instead of editing old ones.