JavaScript Block Scope and Lexical Name Lookup
Quick answer
A block groups statements inside braces. A let or const declared in an ordinary block is visible inside that block and its nested scopes, not in surrounding code. Lexical scope follows the structure of the source.
How it works
When evaluating a name, JavaScript starts with the current lexical environment and searches outward until it finds the binding. A block can read outer bindings; the outer block cannot reach names declared only in the inner block. Braces used for an object literal are not the same as a statement block. The examples here use explicit standalone blocks.
const fee = 4;{ const base = 8; console.log(base + fee);}console.log(fee);Expected output in Node.js:
124The inner block sees both names; the outer code sees fee.
let total = 2;{ const extra = 3; total = total + extra;}console.log(total);Expected output in Node.js:
5Assignment finds the outer binding.
Common mistakes
Reading base after its block ends would produce a ReferenceError in the first example. Do not move declarations outward unless the wider lifetime is actually needed.
Practice
Calculate a subtotal in an inner block and assign the result to an outer variable, then return it.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Block Scope and Lexical Name Lookup — Knowledge Check
Apply the taught concept and reason about the result.
What does let total = 1; { const add = 4; total = total + add; } console.log(total); print?
What happens when code reads a name declared only in a completed inner block?
Where does lexical name lookup begin?
Which statement about a standalone block is correct?
Why keep a temporary subtotal inside its block?