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):
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...
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:
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:
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 birth | A user's current score in a game |
| The price of a product | The number of items in a shopping cart |
| The name of your app | A countdown timer |
| A web address you'll fetch data from | Whether a menu is currently open or closed |