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:
- Inner scope (the
innerfunction) — not found - Outer scope (the
outerfunction) — 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.