const: Boxes With Locks

Grade 1, page 3 of 9. A two-minute read.

Sometimes you have a value that should never change. The number of days in a week. The value of pi. Your birthday. For these, JavaScript gives you const (short for constant):

JavaScript
const daysInAWeek = 7;
console.log(daysInAWeek);

It prints

7

A const is a box with a lock on it. Once you put a value inside, you can't put a different value in. If you try...

JavaScript
const daysInAWeek = 7;
daysInAWeek = 8;

It stops with an error

Uncaught TypeError: Assignment to constant variable.

JavaScript slaps your hand away. Nice try, but a week still has seven days. (Sorry. We wanted an extra weekend day too.)

Because you can never put a value in later, you must give a const its value right away, when you create it:

JavaScript
const birthday;

It stops with an error

Uncaught SyntaxError: Missing initializer in const declaration

"Initializer" means "the starting value." JavaScript is saying: "You made a locked box but didn't put anything in it, so it'll be empty forever. That's pointless."

So which should I use, let or const?

Here's the rule most professional developers follow, and it's the one we'll use in this book:

TipThe golden rule

Use const by default. Switch to let only when you know the value will need to change.

Why? Because when you (or someone else) read your code later, seeing const instantly tells you "this value never changes, I don't need to keep track of it." That makes code much easier to understand. And if you accidentally try to change something that shouldn't change, JavaScript will catch the mistake for you.

Use const for...Use let for...
A user's date of birthA user's current score in a game
The price of a productThe number of items in a shopping cart
The name of your appA countdown timer
A web address you'll fetch data fromWhether a menu is currently open or closed

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning