What is block scope?
Block scope means a variable declared with let, const or class inside a pair of braces exists only inside those braces, including if, for, while, try, switch and bare { } blocks.
Before ES2015 JavaScript only had function scope: a var inside an if was visible in the whole function. let and const added block scope, which matches how most other languages work and removes a whole class of bugs.
Where it helps
- Loops:
for (let i = 0; ...)creates a newifor each iteration. Callbacks created inside the loop each capture their own value. - Temporary variables: helpers you only need inside an
ifdisappear afterwards, so they cannot be misused later. - Avoiding accidental overwrites: the same name can be reused safely in separate blocks.
switchcases: wrap a case body in{ }to declareconstvariables without "already declared" errors.
Temporal dead zone
Block-scoped variables exist from the start of the block but cannot be read before their declaration line; doing so throws a ReferenceError.
var ignores blocks
var inside a block is still function-scoped, which is a common source of confusion in older code.
Code example
1if (true) {2 let message = "inside";3 const limit = 10;4 var leaked = "var ignores the block";5}6console.log(typeof message, typeof limit); // undefined undefined7console.log(leaked); // "var ignores the block"89// switch: braces give each case its own block10function describe(n) {11 switch (n) {12 case 1: {13 const label = "one";14 return label;15 }16 case 2: {17 const label = "two"; // no "already declared" error18 return label;19 }20 default:21 return "many";22 }23}24console.log(describe(1), describe(2), describe(9)); // one two many2526// Each loop iteration gets its own `i`27const fns = [];28for (let i = 0; i < 3; i++) fns.push(() => i);29console.log(fns.map((f) => f())); // [0, 1, 2]
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.