Variables have a territory
Scope is the region of code where a variable exists. The rule in modern JavaScript is simple: a let or const variable lives inside the nearest pair of curly braces { } that contains it. That includes function bodies, if blocks, and loop bodies.
Two directions to remember:
- Inner code can see outward. A function body can read variables declared outside it.
- Outer code cannot see inward. A variable born inside braces is invisible outside them.
const site = "Hack University"; function welcome(name) { const message = `Welcome to ${site}, ${name}`; // site is visible here return message; } // message is NOT visible here
Declaring a new variable inside a function with the same name as an outer one creates a separate inner variable that temporarily hides the outer one. That is called shadowing, and it is a frequent source of "why did my variable not change?" confusion.
Code exercise · javascript
Run it. increment reaches OUT to the shared counter. reset declares its own inner counter (shadowing), so the outer one is untouched.
Code exercise · javascript
Your turn. This program crashes: msg only exists inside makeMessage. Fix it the right way, by returning the value and printing what the call gives back. It should print done.
Quiz
A const declared inside an if block is read two lines AFTER the block closes. What happens?