JavaScript Tutorial
JavaScript Let
let declares a name you can reassign. It is block-scoped: a let inside { } stays inside { }.
Declare with let
let creates a name in the current block. You may give it a value on the same line, or assign later. After that, you can store a new value in the same name.
Example
let city = "Paris";
console.log(city);
city = "Lisbon";
console.log(city);The name city stays. The string inside it changes. That is reassignment.
Click Try it in JavaScript to open /javascript/try.
Reassign, do not redeclare
Write city = "Lisbon" to change the value. Do not write let city again in the same block. A second declaration with the same name is a syntax error.
Example
let n = 1;
n = 2;
console.log(n);
// let n = 3; // SyntaxError: already declaredOne let per name per block. After that, only assignment.
Block scope
A block is the code between braces: the body of an if, a loop, or a pair of braces you write yourself. A let declared inside a block is not visible outside that block.
Example
let score = 12;
if (score >= 10) {
let message = "pass";
console.log(message);
}
// console.log(message); // ReferenceError: message is not defined
console.log(score);score lives in the outer block, so the last log works. message lives only inside the if. That is what “block-scoped” means.
Inner names can reuse a word
An inner block may declare its own let with a name that already exists outside. Inside the block, that inner name wins. Outside, the outer name is unchanged. This is legal. It is also easy to misread. Prefer different names.
Example
let label = "outer";
{
let label = "inner";
console.log(label);
}
console.log(label);The console prints inner, then outer. Two boxes, same word, different blocks.
Use the name after the declaration
You cannot read a let on the lines above its declaration in the same block. The name exists on paper, but it is not ready. That gap is called the temporal dead zone. Declare first, then use.
console.log(n); let n = 1; throws ReferenceError. Move the let to the top of the block.
let vs var
var ignores block braces. A var inside an if still leaks to the function around it. let does not leak. That is the main reason this tutorial useslet.
| let | var | |
|---|---|---|
| Scope | Block | Function |
| Redeclare in same scope | Error | Allowed |
| Visible before the line | No — throws | Yes, as undefined |
When to use let
Use let for a counter, a running total, or any name you will assign more than once. If you never reassign, use const instead. That is the next chapter.