Chapter IX · Scope

Scope Chain

The scope chain is the ordered path — from the current scope outward, one containing scope at a time, all the way to global — that JavaScript follows to resolve a variable name.

01 How It Works

Think of asking a question and passing it up a chain of command: you ask your immediate manager, and if they don't know, they ask theirs, and so on, until someone up the chain has the answer — or you run out of people to ask.

Every scope keeps a reference to the scope that contains it, forming a chain that ultimately ends at the global scope. When code references a variable, the engine checks the current scope's bindings first; if there's no match, it moves to the next scope out, and repeats, until it either finds the name or reaches the end of the chain (global scope) without success — at which point it throws a ReferenceError. Importantly, this lookup only ever travels outward, never inward or sideways: a function can't see variables declared inside a sibling function it doesn't contain.

example.js
let globalVar = "global";

function level1() {
  let midVar = "mid";
  function level2() {
    console.log(globalVar); // not found locally, so the engine walks the chain
  }
  level2();
}
level1();
  1. 1. Look for the variable in the current (innermost) scope.

  2. 2. If not found, move outward to the next enclosing scope and check there.

  3. 3. Repeat until the variable is found (lookup stops there) or the global scope is reached with no match (ReferenceError).

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
let base = 10;

function addBase(n) {
  return n + base; // "base" isn't local to addBase, so the chain is walked outward to global
}
console.log(addBase(5)); // 15

function outer() {
  let x = 1;
  function middle() {
    let y = 2;
    function inner() {
      console.log(x + y); // walks past middle's scope, then outer's scope, finds both
    }
    inner();
  }
  middle();
}
outer(); // 3

Key Takeaway

Variable lookup always travels outward through the scope chain, one enclosing scope at a time, and it stops the instant a match is found — never continuing further than necessary.

Related Concepts