Variable Scope: Global, Function and Block
In short: every variable has a region of code where it exists, called
its scope — outside that region, the name simply is not there. let and
const live inside the braces { } where they were declared, whether that
is an if, a loop, or a bare block. var ignores block braces entirely and
belongs to the whole surrounding function (or the global scope, if it is not
inside one). A name declared outside every function and block is global
and visible everywhere. Looking a name up always walks outward, from
where it is used to the braces around it.

Read a global name from inside a function
Code inside a function can see names declared outside it — lookup walks outward until it finds a match:
show declares no mood of its own, so the lookup steps outward one level
and finds the global one, printing calm.
A block-scoped counter leaking out of an if
let and const treat every pair of braces as a wall. Declare one inside
an if, then read it from outside, and there is nothing to find:
This throws ReferenceError: n is not defined — n's scope ended with the
if block. Swap let for var and the story changes completely:
This prints 1. var ignores the if's braces and belongs to the
surrounding scope, so the name is still there once the block ends.
A variable declared inside a function, read outside it
Unlike a bare block, a function's braces stop even var:
This throws ReferenceError: secret is not defined. var respects
function boundaries; it only ignores the smaller block boundaries (if,
for, a bare { }) that sit inside a function.
The trap: a loop counter that escapes
Because var ignores block braces, a for loop's counter written with
var is still readable after the loop ends:
This prints 3 — the value that failed the loop's condition. With let,
the same read would throw a ReferenceError, because let i belongs only
to the loop's block. This is one of the clearest reasons modern code
defaults to let: it keeps a loop's counter from leaking into code that
should never see it.
The code
for (let i = 0; i < 3; i++) { } console.log(i);
Quick practice
What does let mood = "calm"; function show() { console.log(mood); } show(); log?
What does if (true) { let n = 1; } console.log(n); do?
At the top level of a script, what does if (true) { var n = 1; } console.log(n); log?
What does function load() { var secret = 42; } load(); console.log(secret); do?
What does for (var i = 0; i < 3; i++) {} console.log(i); log?
🎯 Your turn
Explain what
function total() { for (let i = 0; i < 2; i++) { var sum = i; } console.log(sum); console.log(i); } total();
does, line by line, in terms of scope.
Write your explanation and submit it — there's no code to run here, just your reasoning.
