Chapters

FundamentalsChapter 9 of 21

const

A name that cannot be pointed somewhere else, and what that does not protect.

A name that stays put

const declares a name that cannot be reassigned. It must be given a value immediately.

JavaScript

JavaScript

const rate = 0.19;

try {
  rate = 0.2;
} catch (error) {
  console.log(error.name + ': ' + error.message);
}

Output

TypeError: Assignment to constant variable.

It locks the name, not the value

This is the part that surprises people. const stops the name pointing somewhere else. It does nothing to the thing it points at.

JavaScript

JavaScript

const scores = [10, 20];

scores.push(30);
scores[0] = 99;

console.log(scores);

Output

[99, 20, 30]

The array was changed throughout and const did not complain, because scores still points at the same array. Only reassigning the name itself is forbidden.

JavaScript

JavaScript

const settings = { theme: 'dark' };

settings.theme = 'light';
settings.compact = true;

console.log(settings);

Output

{theme: "light", compact: true}

Gotcha

const is not immutability. If you need the contents fixed as well, Object.freeze is the nearest thing, and it only goes one level deep.

JavaScript

JavaScript

const config = Object.freeze({ retries: 3 });

config.retries = 10;

console.log(config.retries);

Output

3

Why prefer it

Most variables are never reassigned. Declaring them const says so, and a reader scanning the code can stop wondering whether the value changes further down.

It also catches real mistakes: a typo that reassigns instead of comparing becomes an error rather than a silent overwrite.

Test yourself

2 questions

What does const prevent?

Show the answer

Pointing the name at a different value The binding is fixed; the contents of an object or array behind it are not.

Why does pushing to a const array work?

Show the answer

The name still points at the same array Nothing was reassigned, so nothing const cares about happened.

Next chapter

var

The old declaration, why it behaves oddly, and why you will still meet it.