Course outline · 0% complete

0/29 lessons0%

Course overview →

Scope: who can see what

lesson 6-3 · ~9 min · 20/29

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.

program scope: const site = "Hack University"function welcome(name): const message = ...if block: let attempt = 1can read attempt, message, name, sitelooking outward always works, looking inward never does
Scopes follow the braces and nest. Code in an inner scope can read every enclosing scope; outer code cannot reach a variable declared inside.

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?