CyberStars

let

Your phone's battery doesn't stay at 80% all day. It goes down when you use the phone, and up when you charge it. Some values are like that: they change while the program runs. For those, const doesn't work.

let

let score = 0;
console.log("Score:", score);

score = 10;
console.log("Score:", score);
Score: 0
Score: 10

let makes a name whose value can change. You write let once, when you make the name. After that, you use the name alone to give it a new value: score = 10, without let.

A new value from the old one

Most of the time, the new value comes from the old one:

let score = 10;
score = score + 5;
console.log("Score:", score);
Score: 15

Read the second line from right to left. Take what is in score (10), add 5, and put the result back in score. Now it holds 15.

let or const?

Ask: will this value change while the script runs?

  • No: const. The minutes in an orbit, a club's name.
  • Yes: let. A score, a number of people, a battery level.

If you're not sure, start with const. If you need to change it later, the console tells you, and you change it to let.

You may also see var in older code. It's an old way to write let, and it can surprise you. Don't use it.

Break it on purpose

Write let twice for the same name:

let score = 0;
let score = 10;

You get a SyntaxError, because the name already exists. Only the first time gets let.


Mission: A ship docks

What you will see: when crew.html opens, the console shows these lines, with its other lines:

Crew on board: 4
Crew on board: 6

A supply ship arrives at the station, and two new crew members come on board.

  • The console shows Crew on board: 4, then Crew on board: 6.
  • The number of crew is kept under one name.
  • The script adds 2 to the value that name already has. It doesn't type 6.
  • The console shows no errors.