JavaScript·Intermediate·Coding·1 min read
How do function scope and block scope differ?
Short interview answer
var and function declarations in ordinary functions are function-scoped, subject to additional block-function rules. let, const, and class are scoped to the nearest block. A for loop with let creates per-iteration bindings used by closures.
Example
if (true) { var a = 1; let b = 2;}console.log(a); // 1 — var ignores the blockconsole.log(b); // ReferenceError — let is block-scopedKey takeaway
Explain the underlying mental model clearly, then support it with a concrete example and its trade-offs.