The let Keyword
let declares a block-scoped variable that can be reassigned.
Syntax
let count = 0;
count = count + 1;let declares a variable whose value can change later. It is block-scoped, meaning it only exists inside the { } block where it is declared.
Reassigning
You can change a let variable as many times as you like β but you declare it with let only once.
Example
Loading editorβ¦
Press Run to execute the code.
When to use it
- Track a loop counter variable that should not be accessible outside the for-block.
- Store form input state that may change as the user edits fields before submission.
- Switch a UI mode variable between "dark" and "light" when the user toggles the theme.
More examples
Block-scoped loop counter
Shows that a let variable declared in a for-loop header is scoped to that block only.
for (let i = 0; i < 3; i++) {
console.log(i);
}
// console.log(i); // ReferenceError β i is not defined hereReassign a mutable state value
Demonstrates that let allows the variable to be reassigned, unlike const.
let theme = "light";
theme = "dark";
console.log(theme); // darkTemporal dead zone
Illustrates the temporal dead zone: accessing a let variable before its declaration throws a ReferenceError.
// console.log(count); // ReferenceError: cannot access before init
let count = 10;
console.log(count); // 10
Discussion