Sub topic 4
let, const, and Block Scope
This chapter assumes you can write functions, if statements, and for loops. It also assumes you have read the previous chapter on how var is scoped to the whole function. Here you will see how let and const follow a tighter rule: they belong to the nearest enclosing block.
What Counts as a Block
A block is any group of statements wrapped in curly braces { }. These are the common ones:
- The body of an
if,else,for,while, ordo...while - A
try,catch, orfinallyclause - The body of a
switchstatement - A bare block: braces standing on their own with no keyword in front
A variable declared with let or const exists from its declaration to the closing brace of its block. Code outside that block cannot see it. var ignores every one of these braces except a function body.
Comparing the Three Keywords Inside a Block
function demo() {
if (true) {
var a = 1;
let b = 2;
const c = 3;
}
console.log(a); // 1: var belongs to the function
console.log(typeof b); // 'undefined': b does not exist out here
console.log(typeof c); // 'undefined'
}
demo();typeof returns 'undefined' for a name that is not declared in any scope it can reach. If you read the variable directly, you get an error:
if (true) {
let message = 'hello';
console.log(message); // 'hello'
}
try {
console.log(message);
} catch (e) {
console.log(e.name); // 'ReferenceError'
}A ReferenceError means the engine searched every reachable scope and found no binding for that name. A binding is the link between a name and the place that stores its value.
How Lookup Works Across Nested Blocks
Each block creates its own scope. When code uses a name, the engine looks in the current block first. If the name is not there, it moves outward one scope at a time until it reaches the global scope. Inner code can see outer variables. Outer code never sees inner ones.
Shadowing
If an inner block declares a name that an outer scope already uses, the inner declaration shadows the outer one. Inside the block, the name refers to the inner variable. The outer variable is still there, just hidden.
const level = 'outer';
{
const level = 'inner';
console.log(level); // 'inner'
}
console.log(level); // 'outer'Shadowing is legal, but it makes code harder to follow. Linters such as ESLint can flag it with the no-shadow rule.
Using Bare Blocks to Limit Lifetime
A bare block lets you keep temporary variables from leaking into the rest of a function:
function summarize(scores) {
let average;
{
const total = scores.reduce((sum, s) => sum + s, 0);
average = total / scores.length;
}
// total is not visible here, so it cannot be reused by mistake
return average;
}
console.log(summarize([80, 90, 100])); // 90In practice, extracting a small helper function usually reads better. The bare block is still useful when you want a narrow scope without adding a new function.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| Declaring with `let` inside `if`, then using it after the `if` | `ReferenceError` | Declare it before the block, assign it inside |
| Declaring the same `let` name in two `case` clauses of a `switch` | `SyntaxError`, because all cases share one block | Wrap each case body in its own `{ }` |
| Expecting a loop counter declared with `let` to exist after the loop | `ReferenceError` | Declare the counter before the loop if you need it later |
Here is the switch fix:
function describe(kind) {
switch (kind) {
case 'a': {
const label = 'Alpha';
return label;
}
case 'b': {
const label = 'Beta';
return label;
}
default:
return 'Unknown';
}
}
console.log(describe('b')); // 'Beta'Later chapters cover what happens when you use a let or const variable before its declaration line, and how let gives each loop iteration a fresh binding.
Exercise
What does this code print, and why? let x = 1; if (true) { let x = 2; if (true) { console.log(x); } } console.log(x);
Show answer
It prints 2, then 1. The inner console.log finds x in the nearest enclosing block that declares it, which is the outer if block where x is 2. The final console.log runs at the top level, where the inner x is out of scope, so it reads the outer x, which is 1.
Exercise
A function declares let result; inside an if block and returns result after the block. Calling it throws a ReferenceError. How do you fix it while still using let?
Show answer
Move the declaration let result; above the if block, then assign result = ... inside the block. The variable then belongs to the function body's scope, so the return statement can reach it.