Sub topic 3
Why const Does Not Make Data Immutable
This chapter assumes you know how to declare variables with let and const, work with objects and arrays, and that you have read the previous chapters on references and mutation bugs. A common belief is that const makes data unchangeable. It does not. const locks the variable. It does not lock the value the variable points to.
Bindings and values are separate things
A binding is the link between a variable name and a value. const creates a binding that cannot be reassigned. The value at the end of that binding works the same way it would with let. Primitives such as numbers and strings cannot be changed in place anyway. Objects and arrays can be.
const user = { name: 'Ada' };
user.name = 'Grace'; // allowed: the object itself is mutable
console.log(user.name); // 'Grace'
try {
user = { name: 'Linus' }; // rebinding is what const forbids
} catch (err) {
console.log(err instanceof TypeError); // true
console.log(err.message); // Assignment to constant variable.
}The first assignment changes a property on the object, and const allows it. The second assignment tries to point user at a different object, and const blocks it.
What const actually guarantees
| Operation | `let` | `const` |
|---|---|---|
| Reassign the variable | Allowed | TypeError |
| Change an object property | Allowed | Allowed |
| `push` onto an array | Allowed | Allowed |
| Delete a property | Allowed | Allowed |
Arrays behave the same way:
const items = [1, 2];
items.push(3);
items[0] = 99;
items.length = 1;
console.log(items); // [99]All three lines change the array that items points to, and none of them is an error.
Common errors
Treating const as a safety guarantee
Developers sometimes declare shared configuration with const and assume nothing can modify it:
const DEFAULTS = { retries: 3, timeout: 1000 };
function makeOptions(overrides) {
const options = DEFAULTS; // copies the reference, not the object
options.retries = overrides.retries;
return options;
}
makeOptions({ retries: 10 });
console.log(DEFAULTS.retries); // 10, the "constant" was changedDEFAULTS was never reassigned, so const had nothing to object to. Because options refers to the same object, the function's edit shows up in DEFAULTS. The fix is to build a new object, which the next chapter covers.
Expecting const in a parameter or loop to protect the argument
function rename(person) {
person.name = 'Unknown'; // mutates the caller's object
}
const ada = { name: 'Ada' };
rename(ada);
console.log(ada.name); // 'Unknown'
for (const p of [ada]) {
p.name = 'Changed'; // const p only stops reassigning p
}
console.log(ada.name); // 'Changed'So how do you get immutable values?
There are two broad approaches, and later chapters cover both:
- By convention: never mutate. Create new objects and arrays with spread syntax and non-mutating methods.
- By enforcement: make the object itself reject changes with
Object.freeze.
const pairs well with either approach. Used together, the variable can't be reassigned and its value won't be changed in place.
Exercise
After this code runs, what are the values of list and copy, and does any line throw? const list = [1, 2]; const copy = list; copy.push(3); list[0] = 0;
Show answer
Nothing throws. list and copy refer to the same array, so both show [0, 2, 3]. const only forbids reassigning list or copy. It does not forbid push or index assignment.
Exercise
Which of these lines throws a TypeError, given const cfg = { a: 1 };? (1) cfg.a = 2; (2) delete cfg.a; (3) cfg = {}; (4) cfg.b = 3;
Show answer
Only line 3 throws, because it reassigns the const binding. Lines 1, 2, and 4 change the object, and const allows that.