Sub topic 3
Why const Does Not Make Data Immutable
This chapter assumes you know how JavaScript variables, functions, and scope work, and that you can create objects and arrays. It also builds on the previous chapter's idea that a variable holding an object stores a reference to that object, not the object itself.
Many developers first meet const and read it as "constant data." The keyword promises something narrower. const says that a name will always point to the same thing. It says nothing about whether that thing can change. If you mix up these two ideas, you get code that looks safe but still lets data change in places you did not expect.
Bindings and Values Are Different Things
A binding is the link between a name in your code and a value in memory. A value is the data itself: a number, a string, an object, an array.
When you write const user = { name: 'Ada' }, JavaScript does two things:
- It creates an object
{ name: 'Ada' }somewhere in memory. - It creates a binding called
userthat holds a reference to that object.
const applies to step 2 only. You cannot reassign the binding, so user will always refer to that same object. The object from step 1 stays an ordinary mutable object. You can still add, change, and delete its properties.
The following example shows both halves of the rule.
const user = { name: 'Ada' };
user.name = 'Grace'; // allowed: the object is mutable
user.role = 'admin'; // allowed: adding a property
delete user.role; // allowed: removing a property
console.log(user); // { name: 'Grace' }
try {
user = { name: 'Linus' }; // not allowed: rebinding the name
} catch (err) {
console.log(err.name, err.message); // TypeError Assignment to constant variable.
}Arrays work the same way, because arrays are objects:
const scores = [10, 20];
scores.push(30); // allowed
scores[0] = 99; // allowed
scores.sort((a, b) => a - b);
console.log(scores); // [20, 30, 99]
try {
scores = []; // not allowed
} catch (err) {
console.log(err.message); // Assignment to constant variable.
}What const Actually Guarantees
The table below sets out what const prevents and what it leaves alone.
| Operation | Example | Allowed with `const`? |
|---|---|---|
| Reassign the variable | `user = {}` | No, throws `TypeError` |
| Declare without a value | `const x;` | No, `SyntaxError` |
| Change a property | `user.name = 'Grace'` | Yes |
| Add or delete a property | `user.age = 36`, `delete user.age` | Yes |
| Call mutating array methods | `list.push(1)`, `list.sort()` | Yes |
| Change the array length | `list.length = 0` | Yes |
| Mutate through another variable | `const alias = user; alias.name = 'X'` | Yes |
The guarantee is still useful. When you read const user at the top of a function, you know that every later mention of user in that scope refers to the same object. You never have to scan for a line that swaps it out for something else. That makes code easier to follow. It does not protect the object's contents.
Why const Looks Immutable With Primitives
Confusion often starts because const with a primitive does behave like a true constant:
const limit = 10;
const greeting = 'hello';
// limit++; // TypeError: the only way to change it is reassignment
const shout = greeting.toUpperCase();
console.log(greeting); // 'hello'
console.log(shout); // 'HELLO'That effect does not come from const. Primitives (numbers, strings, booleans, null, undefined, symbols, and bigints) are immutable values in JavaScript. No operation changes the number 10 or the string 'hello' in place. String methods such as toUpperCase always return a new string. The only way to "change" a primitive variable is to point it at a different value, and const forbids that. So with primitives, the two rules together give you immutability. With objects, only one of them applies.
Common Errors and Gotchas
Expecting a const array to be read-only
A common bug comes from treating a const array or object as a safe default that cannot be modified:
const DEFAULT_TAGS = ['general'];
function createPost(title) {
return { title, tags: DEFAULT_TAGS };
}
const a = createPost('First');
const b = createPost('Second');
a.tags.push('urgent');
console.log(b.tags); // ['general', 'urgent']
console.log(DEFAULT_TAGS); // ['general', 'urgent']The upper-case name and const both suggest a fixed value, but every post shares one array. A push through any post changes the "constant" for everyone. Later chapters fix this by copying the array or freezing it.
Clearing an array in place versus replacing it
Because const blocks list = [], developers sometimes clear an array with list.length = 0 or list.splice(0) instead. Those calls compile without complaint, but they mutate the shared array:
const items = [1, 2, 3];
const snapshot = items; // someone else holds a reference
items.length = 0; // mutates the shared array
console.log(snapshot); // []
let liveItems = [1, 2, 3];
const savedView = liveItems;
liveItems = []; // rebinding: creates a new array
console.log(savedView); // [1, 2, 3], the old array is untouchedIn this case, let with reassignment is the more immutable option. It leaves the old array alone and points the name at a new one. Picking const and then mutating to work around it gives you the opposite of what you wanted.
const in loops
Each iteration of for...of and for...in creates a fresh binding, so const works there. A classic for loop updates one counter in place, so const fails on the first increment:
for (const n of [1, 2, 3]) {
console.log(n); // 1, 2, 3: a new binding per iteration
}
try {
for (const i = 0; i < 3; i++) {
console.log(i); // prints 0, then i++ throws
}
} catch (err) {
console.log(err.message); // Assignment to constant variable.
}This is another sign that const concerns the binding. The loop variable n gets a new binding each time round, and nothing about the values in the array becomes protected.
Function parameters are not const, and not copies
Parameters behave like let bindings. You can reassign them, and reassignment does not affect the caller. Mutating the object they refer to does affect the caller:
function rename(person) {
person.name = 'Changed'; // visible to the caller
person = { name: 'Local' }; // only rebinds the local parameter
return person;
}
const original = { name: 'Ada' };
const result = rename(original);
console.log(original.name); // 'Changed'
console.log(result.name); // 'Local'Declaring original with const did not stop rename from changing it. A binding in one scope has no control over what other code does with the same object.
Imported bindings are read-only, but exported objects are not
ES module imports are read-only bindings. You cannot assign to an imported name, even if the exporting module declared it with let. The object behind the import can still be mutated, and every importer sees the change:
// config.js
export const settings = { debug: false };// main.js
import { settings } from './config.js';
settings.debug = true; // allowed: mutates the shared module object
console.log(settings.debug); // true, and true for every other importer too
try {
settings = {}; // not allowed: imports are read-only bindings
} catch (err) {
console.log(err.name); // TypeError
}Shared module state like this causes a lot of "it works alone but breaks in the full app" bugs. One module flips a flag on a shared config object, and an unrelated module changes behavior.
Choosing Between const and let
The decision is about the binding, never about the data:
| Question | Choose |
|---|---|
| Will this name always refer to the same value in this scope? | `const` |
| Does the name need to point to different values over time, such as an accumulator or a reassigned state variable? | `let` |
| Do I need the object's contents to stay unchanged? | Neither keyword helps. Use copying patterns, `Object.freeze`, or a library |
When you work with immutable data patterns, const and immutable values fit together well. You keep each binding fixed, and when data needs to change, you create a new value and bind it to a new name, or return it from a function. The rest of this tutorial covers the techniques for creating those new values.
Exercise
What does this code print, and why? const cart = { items: ['apple'] }; const copyRef = cart; copyRef.items.push('pear'); console.log(cart.items.length);
Show answer
It prints 2. const only stops cart from being reassigned. copyRef holds a reference to the same object, so pushing onto copyRef.items changes the one array that both names reach.
Exercise
A teammate writes const queue = loadJobs(); and later, to empty it, writes queue.length = 0, because queue = [] throws. Another module holds a reference to the original queue for logging. What goes wrong, and how would you fix it?
Show answer
Setting length to 0 mutates the shared array, so the logging module suddenly sees an empty queue. Declare it with let queue = loadJobs(); and reassign queue = []. That binds the name to a new array and leaves the original untouched for anyone still holding it.
Exercise
Why does for (const i = 0; i < 3; i++) throw while for (const x of [1, 2, 3]) works?
Show answer
The classic for loop updates a single binding with i++, which is a reassignment and is not allowed on a const binding. for...of creates a fresh binding for each iteration and never reassigns any of them.
Exercise
Is a const-declared string immutable because of const? Explain.
Show answer
Not mainly. Strings are immutable primitive values, so no operation can change one in place. const adds only the guarantee that the variable cannot be pointed at a different string. Together they act like a true constant, but the immutability of the value comes from the string being a primitive.