JavaScript Block Scope in Depth
Block scope gives each block its own variables. A let inside a block hides an outer variable with the same name, and the outer one returns when the block ends.
A block let hides the outer one
The block declares its own color. Inside the block, the inner color wins. Outside, the outer color is back.
let color = "blue";
{
let color = "red";
console.log(color);
}
console.log(color);Nested blocks hide in layers
Each nested block shadows the size again. The prints peel the layers back off, one block at a time.
let size = "large";
{
let size = "medium";
{
let size = "small";
console.log(size);
}
console.log(size);
}
console.log(size);A block variable stays in its block
The secret exists only inside its block. Reading it outside throws, and the catch logs the error name.
{
let secret = "hidden";
console.log(secret);
}
try {
console.log(secret);
} catch (err) {
console.log(err.name);
}Example
let mode = "light";
{
let mode = "dark";
console.log("Inside: " + mode);
{
let mode = "dim";
console.log("Deepest: " + mode);
}
console.log("Back to: " + mode);
}
console.log("Outside: " + mode);Key points
- Block scope: the rule that a let or const belongs to the block where it is declared
- Shadowing: an inner declaration that hides an outer variable with the same name
- The inner variable is visible only inside its block.
- When the block ends, the outer variable is visible again.
- Nested blocks can shadow in layers.
- A block variable cannot be read after its block ends.
In this example, the outer mode is light. The first block shadows it with dark, and the nested block shadows it again with dim. Each block ends in turn, so the prints show dark again, then light.
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 the outer variable read as after a block that shadows it?