Choose const or let

Every name you’ve created in this course so far started with let. Some of those names moved a lot. Your game night score went from 20 to 30 to 35, and in the running-score exercise, your score moved with every update. Other names never moved at all once you’d created them, like the player’s name or the number of slices in a pizza.

JavaScript gives you a second keyword for exactly those names that stay put: const. In this lesson, you’ll learn to choose between const and let for each name in a script, and you’ll meet the two errors that const can cause, so that you can read them and fix them when they show up.

Declare a Name That Stays Put With const

Back to game night. Create a new file named game.js in your scratch folder. The player’s name won’t change during the game, but the score will:

Language: JavaScript Filename: scratch/game.js
const player = "Ada";
let score = 20;
score = score + 10;
console.log(player);
console.log(score);

Save the file and give it a spin in the terminal:

Language: Shell
$ node scratch/game.js
Ada
30

The first line looks just like a let line, with only the keyword swapped. A const declaration creates a name and points it at a value. The name is a constant, which means it’ll point at the same value for as long as the program runs. MDN’s page on the const declaration has the full details.

You might wonder why this is worth a second keyword, since let player = "Ada" would print the same thing. The difference shows up when someone reads the code. A const tells the reader that this name never moves, so they don’t have to scan the rest of the script for a line that changes it. And if you ever write such a line by accident, JavaScript stops you, as you’ll see next.

In the luggage tag picture from earlier, a const tag is tied on with a knot that doesn’t come undone. You can still read the tag as often as you like, and you can use its value in a calculation, but you can’t move the tag to a different value.

Try to Move a const Name

Say that Ada hands her seat to Grace partway through the evening. Replace the code in game.js with this version, which tries to point player at a new value. Before you run it, predict which lines print something and where the script stops:

Language: JavaScript Filename: scratch/game.js
const player = "Ada";
let score = 20;
console.log(player);
score = score + 10;
console.log(score);
player = "Grace";
console.log(player);

Now run it and compare the output with your prediction:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.