Learn JavaScript
❯ variables.scope

Block, Function & Lexical Scope in JavaScript

$concept

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.

$how it works
1

Blocks scope let/const

if (true) { let x = 1; } — x dies at the closing brace; each loop iteration gets fresh bindings.

2

Functions scope var

var inside any block belongs to the whole function — the leak that let/const's block scoping fixed.

3

Lexical lookup

Functions resolve names where defined, not where called — inner functions see outer locals permanently.

4

Shadowing hides outward

An inner let x masks the outer x within its block — legal, occasionally handy, usually a readability cost.

$example
let outer = "O";
function show() {
let inner = "I";
console.log(outer + inner);
}
show();
Output
OI
1outer lives globally, visible everywhere below its declaration.
2show's body sees its own inner plus the lexically enclosing outer — OI concatenates and prints.
3inner dies with the call; outer persists — scope lifetimes differ by declaration site.
$use cases
Containing loop counters with block-scoped let
Reading closures as lexical scope surviving function return
Avoiding var's function-wide leaks in legacy code
Flagging accidental shadowing in reviews

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.