Block Scope with Let and Const
You'll learn how let and const create block-scoped bindings that interact with the lexical scope chain differently from var.
What is Block Scope?
While function scope (like you've seen with var) creates a new lexical environment for each function, block scope creates a new lexical environment for each set of curly braces {}. This includes if statements, for loops, while loops, and standalone blocks.
When you declare a variable with let or const inside a block, it only exists within that block and any nested blocks inside it. The scope chain still works the same way—inner blocks can access outer scopes—but now those scopes can be smaller than entire functions.
How It Works with the Scope Chain
function example() {
const outer = 'function scope';
if (true) {
const inner = 'block scope';
console.log(outer); // ✓ Can access outer scope
console.log(inner); // ✓ Can access current block
}
console.log(outer); // ✓ Still accessible
console.log(inner); // ✗ ReferenceError: inner is not defined
}
Each block with let or const adds a new link to the scope chain. When JavaScript looks up a variable, it searches the current block, then outer blocks, then the function scope, and so on up the chain.
Practical Implications
for (let i = 0; i < 3; i++) {
// Each iteration creates a NEW block scope with a fresh 'i'
}
// console.log(i); // ReferenceError - i doesn't exist out here
Key Takeaway: let and const create block-scoped bindings that extend the lexical scope chain to include any {} block, not just functions, giving you more precise control over variable visibility.