Sub topic 8
const Does Not Mean Immutable
This chapter assumes you know how to create objects and arrays, how to read property values, and the rule from the previous chapter that a const variable cannot be reassigned. Many developers take that rule to mean the value stored in a const can never change. That is wrong, and the mistake causes real bugs.
Bindings and Values Are Separate Things
A variable declaration creates a binding, which connects a name to a value. With primitives such as numbers, strings, and booleans, the distinction rarely matters, because primitives cannot be changed in place. Objects and arrays work differently. The binding holds a reference to the object, and the object itself sits somewhere else in memory.
const locks the binding, so the name must always point to the same object. It places no restriction on the object.
Mutating Through a const Binding
'use strict';
const config = { retries: 3, tags: ['api'] };
config.retries = 5; // allowed: changes a property
config.tags.push('beta'); // allowed: changes the array
config.timeout = 1000; // allowed: adds a property
console.log(config); // { retries: 5, tags: [ 'api', 'beta' ], timeout: 1000 }
try {
config = { retries: 0 }; // not allowed: rebinds the name
} catch (e) {
console.log(e.name); // 'TypeError'
}Each of the first three lines changes the object, and all three succeed. Only the reassignment fails. The same rule applies to arrays: const list = [] lets you call push, pop, and sort, but not list = [].
Making the Value Unchangeable with Object.freeze
When you want the object itself to stay fixed, use Object.freeze. It makes an object's existing properties read-only and blocks new properties from being added or old ones removed.
'use strict';
const settings = Object.freeze({ retries: 3, limits: { max: 10 } });
try {
settings.retries = 5;
} catch (e) {
console.log(e.name); // 'TypeError'
}
settings.limits.max = 99; // allowed: freeze is shallow
console.log(settings.retries, settings.limits.max); // 3 99
console.log(Object.isFrozen(settings)); // true
console.log(Object.isFrozen(settings.limits)); // falseFreeze Is Shallow
Object.freeze only affects the object you pass to it. Nested objects and arrays stay mutable, as settings.limits shows above. To lock an entire structure, freeze it recursively:
function deepFreeze(obj) {
for (const value of Object.values(obj)) {
if (value !== null && typeof value === 'object') {
deepFreeze(value);
}
}
return Object.freeze(obj);
}
const theme = deepFreeze({ colors: { primary: '#0af' }, sizes: [12, 16] });
console.log(Object.isFrozen(theme.colors), Object.isFrozen(theme.sizes)); // true trueComparing the Two Tools
The two tools answer different questions, and you can combine them.
| Declaration | Reassign the name? | Change properties? |
|---|---|---|
| `let obj = {}` | Yes | Yes |
| `const obj = {}` | No | Yes |
| `let obj = Object.freeze({})` | Yes | No (top level) |
| `const obj = Object.freeze({})` | No | No (top level) |
Common Errors
- Assuming const protects shared state. A function that receives a
constobject can still change it. If callers must not change it, freeze it or pass a copy. - Forgetting freeze is shallow. Freezing a config object does not protect its nested arrays.
- Silent failures in sloppy mode. A write to a frozen object that seems to do nothing usually means the code is not running in strict mode.
- Expecting a performance gain. Neither
constnorObject.freezeis a dependable optimization. Use them to make your intent clear.
Exercise
Given const cart = { items: ['apple'] };, which of these lines throw a TypeError in strict mode: (1) cart.items.push('pear'), (2) cart.items = [], (3) cart = { items: [] }? What changes if the declaration is const cart = Object.freeze({ items: ['apple'] });?
Show answer
With the plain object, only (3) throws, because it reassigns the const binding. Lines (1) and (2) change the object, which const allows. With the frozen object, (2) also throws, because items is now a read-only property, and (3) still throws. Line (1) still succeeds, because freeze is shallow and the items array itself is not frozen.
Exercise
Write a line that makes const point = { x: 1, y: 2 }; reject point.x = 5 without changing the declaration.
Show answer
Object.freeze(point); freezes the object in place. After that call, point.x = 5 throws a TypeError in strict mode and is silently ignored in sloppy mode.