Course contentsShow
← JavaScript
Lesson 487 of 2,72313. ClosuresFree lesson

Scope Chain Fundamentals

How JavaScript searches through nested scopes from innermost to outermost to resolve variable references.

Scope Chain Fundamentals

What you'll learn: How JavaScript resolves variable names by searching through nested scopes from the inside out.

When you reference a variable in JavaScript, the engine doesn't just look in one place—it searches through a chain of scopes. This chain works like a ladder: JavaScript starts at the innermost scope (where the code is currently executing) and climbs outward through each parent scope until it finds the variable or reaches the global scope.

How the Search Works

Think of nested scopes like rooms inside rooms. When you're in the innermost room and ask for something, JavaScript first checks this room. If it's not here, it checks the next room out, then the next, and so on, until it either finds what you need or runs out of rooms (scopes) to check.

const global = 'I am global';

function outer() {
  const outerVar = 'I am in outer';
  
  function inner() {
    const innerVar = 'I am in inner';
    
    console.log(innerVar);  // Found immediately in inner scope
    console.log(outerVar);  // Climbs up to outer scope
    console.log(global);    // Climbs up to global scope
  }
  
  inner();
}

outer();

When inner() executes and looks for outerVar, JavaScript searches:

  1. Inner scope (the inner function) — not found
  2. Outer scope (the outer function) — found! ✓

The search stops as soon as a match is found. This "climbing outward" path is the scope chain.

Shadowing

If a variable exists in multiple scopes, the closest one wins—the chain never needs to climb further.

Key Takeaway: JavaScript resolves variables by searching from the current scope outward through parent scopes until the variable is found or the global scope is exhausted. This outward path is the scope chain.