Block Scope
Block Scope
Section titled “Block Scope”Introduction
Section titled “Introduction”Block scope confines variables to the block {} where they are declared. let and const have block scope, while var does not.
Visual Explanation
Section titled “Visual Explanation”flowchart LR A["{ let x = 1; }"] B["x is accessible here"] C["x is NOT accessible outside"]
A --> B A --> C C --> D["ReferenceError!"]let and const are Block Scoped
Section titled “let and const are Block Scoped”{ let x = 10; const y = 20; console.log(x, y); // 10, 20}
console.log(x); // ReferenceErrorconsole.log(y); // ReferenceErrorvar is NOT Block Scoped
Section titled “var is NOT Block Scoped”{ var z = 30;}
console.log(z); // 30 — var leaks out of the block!Practical Example
Section titled “Practical Example”// Block scope prevents counter leaksfor (let i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Logs: 0, 1, 2 (each i is block-scoped)
// VS var — all share the same variablefor (var i = 0; i < 3; i++) { setTimeout(() => console.log(i), 100);}// Logs: 3, 3, 3 (only one i)Summary
Section titled “Summary”letandconstare block scopedvaris function scoped (not block scoped)- Block scope prevents variable leakage
- Always prefer
let/constovervar