JavaScript Let
let is the keyword that declares a variable whose value can change. A let variable can gain its value after the declaration line.
Assign after declaring
The first line declares score with no value. The second line assigns the value 5.
let score;
score = 5;
console.log(score);Reassign the value
score starts at 5 in this program. A later line replaces that value with 8.
let score = 5;
score = 8;
console.log(score);No value yet
This variable holds no value at the log line. The console prints the word undefined for it.
let score;
console.log(score);Example
let level;
level = 1;
console.log(level);
level = 2;
console.log(level);Key points
- A value stored with let can be replaced later.
- A variable can be declared first and given its value on a later line.
- undefined: the value held by a variable that has no value yet
- Scope: the part of a program where a name can be used
- Declaring the same name with let twice in the same scope is an error.
In this example, the first statement declares level with no value. The second statement assigns the value 1. The third statement prints that value. The fourth statement reassigns level to 2, and the last statement prints the new value.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does a let variable hold before any value is assigned?