Block, Function & Lexical Scope in JavaScript
Scope answers where a name is visible: block scope ({ } with let/const — each block its own names), function scope (var and parameters live for the whole function), and the global scope above all. JavaScript uses lexical (static) scoping — a function's variable lookup follows where it was written, not where it runs — which is what makes closures possible.
Scope chains nest outward: missing locally means checking the enclosing function, then the next, then global — ending in ReferenceError if nobody declares it. Shadowing (redeclaring a name inward) is legal and occasionally useful, usually confusing.
Blocks scope let/const
if (true) { let x = 1; } — x dies at the closing brace; each loop iteration gets fresh bindings.
Functions scope var
var inside any block belongs to the whole function — the leak that let/const's block scoping fixed.
Lexical lookup
Functions resolve names where defined, not where called — inner functions see outer locals permanently.
Shadowing hides outward
An inner let x masks the outer x within its block — legal, occasionally handy, usually a readability cost.
let outer = "O";function show() { let inner = "I"; console.log(outer + inner);}show();Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.