The Scope Chain

Grade 9, page 7 of 11. A one-minute read.

When JavaScript sees a variable name, how does it find the right box? It follows a simple rule: start in the current scope and look outward, one level at a time, until it finds the variable. If it reaches the global scope and still hasn't found it, you get a ReferenceError.

This path is called the scope chain:

JavaScript
const planet = "Earth";

function country() {
  const nation = "France";

  function city() {
    const town = "Paris";
    console.log(`${town}, ${nation}, ${planet}`);
  }

  city();
}

country();

It prints

Paris, France, Earth

When city needs town, it finds it right in its own scope. For nation, it doesn't find it locally, so it looks one level out, in country, and finds it there. For planet, it looks out again, all the way to the global scope.

The lookup only ever goes outward, never inward. country can't see town, and the global scope can't see nation. One-way windows, remember?

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning