Sub topic 8
const Does Not Mean Immutable
This chapter assumes you already know the material from the earlier chapters: how let, const, and var are declared, and that assigning a new value to a const throws a TypeError. It also assumes you are comfortable with objects, arrays, and strict mode at the level of "it's a mode that makes some silent errors throw."
The most common misreading of const is "this value can never change." That is wrong. The rest of this chapter explains why it is wrong, what const does guarantee, and which tools give you real immutability when you need it.
Bindings and values are separate things
A binding is the link between a name and a value. When you write const limit = 10, the engine creates a binding named limit in the current scope and points it at the value 10.
const puts a rule on the binding: once initialized, it can never point at a different value. It says nothing about the value at the other end of that link.
How much that rule protects you depends on the kind of value:
- Primitives (numbers, strings, booleans,
null,undefined, bigints, symbols) are already immutable. You can't change the number10into11. You can only point a binding at a different number. So aconstprimitive behaves like a true constant. - Objects (plain objects, arrays, functions, Maps, Sets, dates, class instances) are mutable. A
constbinding to an object stops you from pointing the name at a different object. Anyone holding a reference can still change the object's contents.
What const allows and what it blocks
const config = { retries: 3 };
config.retries = 5; // allowed: changes a property of the object
config.timeout = 1000; // allowed: adds a property
delete config.timeout; // allowed: removes a property
console.log(config); // { retries: 5 }
const list = [1, 2, 3];
list.push(4); // allowed: mutates the array
list[0] = 99; // allowed
list.length = 2; // allowed: truncates the array
console.log(list); // [ 99, 2 ]
try {
config = { retries: 1 }; // blocked: reassigns the binding
} catch (e) {
console.log(e.name); // 'TypeError'
}Every operation that writes to the binding is blocked. That includes some that don't look like assignment at first:
| Operation on a `const` binding `x` | Result |
|---|---|
| `x = newValue` | `TypeError` |
| `x += 1`, `x -= 1`, `x ??= y` | `TypeError` |
| `x++`, `--x` | `TypeError` |
| `[x] = [1]` (destructuring into an existing name) | `TypeError` |
| `x.prop = 1`, `x.push(1)` | Allowed if `x` is a mutable object |
Gotcha: const in a classic for loop
This difference trips people up in loops:
for (const item of ['a', 'b']) {
console.log(item); // 'a', then 'b'
}
try {
for (const i = 0; i < 3; i++) {
console.log(i); // prints 0 once
}
} catch (e) {
console.log(e.name); // 'TypeError', thrown by i++
}for...of and for...in create a fresh binding for each iteration, so the binding is never reassigned and const works. A classic three-part for loop has to update its counter, and i++ is a reassignment. The body runs once with 0, and then i++ throws. Use let for counters.
Getting real immutability with Object.freeze
To stop changes to an object's contents, act on the object itself. Object.freeze(obj) makes every own property non-writable and non-configurable and blocks new properties. It returns the same object, so the usual pattern is to pair it with const:
const settings = Object.freeze({ retries: 3, mode: 'safe' });
console.log(Object.isFrozen(settings)); // trueconst and freeze do different jobs, and together they lock down both layers. const stops the name from moving. freeze stops the object from changing.
Gotcha: failed writes are silent in sloppy mode
What happens when you write to a frozen object depends on the mode of the code doing the write:
// Run as a classic script or CommonJS file, not as an ES module
const frozen = Object.freeze({ retries: 3 });
function trySloppy() {
frozen.retries = 5; // silently ignored
console.log(frozen.retries); // 3
}
function tryStrict() {
'use strict';
try {
frozen.retries = 5;
} catch (e) {
console.log(e.name); // 'TypeError'
}
}
trySloppy();
tryStrict();In sloppy mode the assignment fails without telling you, and the bug shows up later as "why is this value still 3?" ES modules and class bodies are always strict, so in modern code you usually get the TypeError. If you save this example as an .mjs file, trySloppy throws too, because the whole module is strict.
const nums = Object.freeze([3, 1, 2]);
try {
nums.push(4);
} catch (e) {
console.log(e.name); // 'TypeError', even in sloppy mode
}Gotcha: freeze is shallow
Object.freeze only affects the object's own properties. If a property holds another object, that inner object stays mutable:
const app = Object.freeze({
name: 'demo',
db: { host: 'localhost', port: 5432 }
});
app.db.port = 9999; // allowed: app.db is a separate, unfrozen object
console.log(app.db.port); // 9999
console.log(Object.isFrozen(app)); // true
console.log(Object.isFrozen(app.db)); // falseTo freeze a whole tree, walk it yourself. This version freezes the parent before visiting the children, so the isFrozen check also stops infinite recursion on circular references:
function deepFreeze(obj) {
Object.freeze(obj);
for (const key of Reflect.ownKeys(obj)) {
const value = obj[key];
if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
deepFreeze(value);
}
}
return obj;
}
const app = deepFreeze({
name: 'demo',
db: { host: 'localhost', port: 5432 },
tags: ['a', 'b']
});
console.log(Object.isFrozen(app.db)); // true
console.log(Object.isFrozen(app.tags)); // trueReflect.ownKeys returns string keys, symbol keys, and non-enumerable keys, so nothing gets skipped.
Gotcha: Map, Set, and Date keep their internal data
Object.freeze locks properties. A Map, Set, or Date stores its data in internal slots that are not properties, so freezing it does not protect that data:
const cache = Object.freeze(new Map());
cache.set('key', 'value'); // works: entries are internal data, not properties
console.log(cache.get('key')); // 'value'
const when = Object.freeze(new Date(0));
when.setFullYear(2030); // works: the date's time value is internal
console.log(when.getFullYear()); // 2030If you need a read-only Map, wrap it in an object that exposes only get and has, or copy it before you hand it to code you don't trust.
Freeze, seal, and preventExtensions
JavaScript has three levels of object locking. They differ in what they forbid:
| Action | `const` only | `Object.preventExtensions` | `Object.seal` | `Object.freeze` |
|---|---|---|---|---|
| Reassign the binding | Blocked | Depends on binding | Depends on binding | Depends on binding |
| Add new properties | Allowed | Blocked | Blocked | Blocked |
| Delete properties | Allowed | Allowed | Blocked | Blocked |
| Change existing values | Allowed | Allowed | Allowed | Blocked |
| Shallow or deep | Not applicable | Shallow | Shallow | Shallow |
Object.seal fits objects with a fixed shape whose values still change, such as a state record with a known set of fields. Object.freeze fits configuration, constants, and lookup tables.
Immutability by convention: copy instead of mutate
Freezing everything is often too much work. A more common practice is to treat objects as immutable by never changing them in place, and to create updated copies instead:
const original = { retries: 3, tags: ['a'] };
const updated = { ...original, retries: 5 }; // shallow copy with one change
const withTag = { ...original, tags: [...original.tags, 'b'] };
console.log(original); // { retries: 3, tags: [ 'a' ] }
console.log(updated); // { retries: 5, tags: [ 'a' ] }
console.log(withTag); // { retries: 3, tags: [ 'a', 'b' ] }
const nums = [3, 1, 2];
const sorted = nums.toSorted(); // ES2023: returns a new array
console.log(nums, sorted); // [ 3, 1, 2 ] [ 1, 2, 3 ]
const deepCopy = structuredClone(original); // full deep copy
deepCopy.tags.push('z');
console.log(original.tags); // [ 'a' ]Spread copies are shallow too. In updated, the tags array is the same array object as original.tags, so updated.tags.push('x') would also change original. When you update a nested value, copy every level on the path down to it, as withTag does. Use structuredClone when you need a full independent copy. toSorted needs Node.js 20 or a current browser.
Common errors at a glance
| Mistake | What actually happens | Fix |
|---|---|---|
| "It's `const`, so nobody can change it" | Object contents can still change | `Object.freeze` or copy-on-write |
| Freezing a nested config with `Object.freeze` | Inner objects stay mutable | `deepFreeze` |
| Writing to frozen objects in sloppy code | Silent failure | Use strict mode or ES modules |
| Freezing a `Map` to make it read-only | `set` and `delete` still work | Wrap it or copy it |
| `for (const i = 0; ...; i++)` | `TypeError` after the first iteration | Use `let` for counters |
Exercise
Predict the output of this code, run as a classic script: const a = Object.freeze({ list: [1] }); a.list.push(2); a.x = 1; console.log(a.list.length, a.x);
Show answer
It prints 2 undefined. Object.freeze is shallow, so the inner array a.list is still mutable and push succeeds. Adding a.x to the frozen object fails silently in sloppy mode, so a.x is undefined. In strict mode, a.x = 1 would throw a TypeError instead.
Exercise
A teammate writes const MAX_USERS = 100; and const DEFAULTS = { theme: 'dark' }; and says both are now constants. Which one is a true constant, and what would you change to make the other one a constant too?
Show answer
MAX_USERS is a true constant, because numbers are primitive and can't be mutated, and const stops reassignment. DEFAULTS can still be mutated (DEFAULTS.theme = 'light' works). Write const DEFAULTS = Object.freeze({ theme: 'dark' });. If it ever holds nested objects, use a deep freeze.
Exercise
Why does const m = Object.freeze(new Map()); m.set('a', 1); succeed, while const arr = Object.freeze([]); arr.push(1); throws a TypeError?
Show answer
Freezing locks an object's properties. Array elements and length are properties, so push tries to write a frozen property and throws (push throws on failure in any mode). A Map stores its entries in internal slots, which are not properties, so set is unaffected by Object.freeze.
Exercise
Rewrite const user = { name: 'Ana', address: { city: 'Lima' } }; user.address.city = 'Cusco'; so that user is not mutated and you get a new object moved with the updated city.
Show answer
const moved = { ...user, address: { ...user.address, city: 'Cusco' } }; Both levels have to be copied. With only { ...user }, moved.address would be the same object as user.address, and changing it would change user too.