Changing a Stored Value with let
Introduction
Welcome to Storing and Calculating with JavaScript Values! This is the first lesson of the second course in our path, and it picks up exactly where the last one left off.
In the previous course, we learned to make a program speak with console.log, to leave notes in comments, to read an error message and repair the line it points at, and - most recently - to store a value under a name with const. Every value we stored stayed exactly as it was for the whole program. That is fine for a shop's name, but a lot of the values a program cares about do change: the number of cups sold today, the running total of a bill, the score in a game.
In this lesson, we will learn how to:
- Declare a variable with
letwhen its value has to change. - Reassign a new value to a variable that already exists.
- Work out the new value from the old one, so a count can go up or down.
- Choose between
constandletfor each value in a program.
By the end, we will have a small program that keeps count of the cups sold at the Corner Cafe as the day goes on.
Why a Value Might Need to Change
Imagine the cafe has sold three cups so far this morning. We store that number:
Then two more customers walk in. The count should now be five. With what we know so far, the natural thing to try is to store the new value under the same name:
When we click Run, JavaScript refuses:
This is a new kind of error, a TypeError, but we already know how to read it. The first line gives the line number, the caret points at the =, and the last line explains: assignment is JavaScript's word for storing a value under a name, and a constant variable is one we declared with const. In plain words, JavaScript is saying that we promised this value would never change, and now we are trying to change it. Node.js prints a few more lines after this one, describing where inside itself the error passed through; we can safely ignore those.
So const is doing exactly what it promised. We need a different way to declare a value that is allowed to change.
Declaring a Variable with let
That way is let. It is written in exactly the same shape as const - the word, the name, =, the value - and it creates a variable in exactly the same way. The one difference is the promise it makes: a let variable is allowed to be given a new value later.
Running this looks just like it would with const:
Nothing has changed yet. let simply leaves the door open.
