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.
Reassigning a Value
To give the variable a new value, we write its name, then =, then the new value - and nothing else. No let this time, because the variable already exists; we are not creating it, we are reassigning it:
When we click Run, the two console.log lines show two different values for the same name:
The moment line 4 runs, cupsSold stops holding 3 and starts holding 5. A variable holds exactly one value at a time, and the old value is simply gone. Any console.log that comes after the reassignment sees the new value; any that came before it already printed the old one.
One thing to hold onto: let appears once, when the variable is born. Every change after that is just name = value. Writing let cupsSold a second time would be asking JavaScript to create a variable that already exists, and it would complain.
Working Out the New Value from the Old One
In the last example we knew the new count was five. Usually a program does not know the new value in advance - it knows how much to add. Two more cups were sold, so the new count should be whatever it was before, plus two. We can say exactly that:
The middle line looks strange at first, because cupsSold appears on both sides of the =. The way to read it is in two steps, and JavaScript always takes them in the same order:
- Work out the right side first.
cupsSold + 2means "the value currently stored undercupsSold, plus two". That is3 + 2, which is5. - Store the result under the name on the left.
cupsSoldnow holds5.
So the line reads as "cupsSold becomes cupsSold plus two", and the output confirms it:
Taking away works the same way, with a - in place of the +. If one customer brings a cup back for a refund, cupsSold = cupsSold - 1; works out the current value minus one and stores that. We will meet - properly, along with the rest of JavaScript's arithmetic, in the next lesson; for now, + to add and - to take away are all we need.
Choosing Between const and let
Now that we have two ways to declare a variable, which should we use? The rule is simple and worth making a habit:
- Start with
const. If a value is never reassigned,constsays so, and JavaScript will catch us if we change it by mistake. - Switch to
letonly when the value has to change. The wordletis then a signal to anyone reading the program: "watch this one, it moves."
Reading a program becomes easier when the declarations tell the truth. A let that is never reassigned makes a reader wonder where the change happens; a const that needs to change stops the program with the TypeError we saw. In the Corner Cafe, the shop's name is a const and the running count of cups is a let.
The Full Program
Let's put the whole lesson into one file:
When we click Run, we get three lines - the count before and after the change, and the shop name that never changed:
Look at the commented-out line near the end. It is there as a reminder: if we removed the // and let it run, JavaScript would stop with TypeError: Assignment to constant variable. and the last console.log would never be reached. The comment keeps the lesson in the file without breaking the program.
Conclusion and Next Steps
Great work! In this lesson, we learned that const refuses to be reassigned and reports a TypeError if we try, that let declares a variable whose value is allowed to change, and that reassigning is written as name = value with no let in front. We saw that the right side of = is worked out first and then stored under the name on the left, which is why cupsSold = cupsSold + 2 makes perfect sense, and we adopted the habit of reaching for const first and let only when a value really has to move.
Next up are a few practice tasks where we change a value, build a new one from the old one, and decide which declaration each value deserves. Let's keep counting!
