Sub topic 5
How the Scope Chain Resolves Names
This chapter assumes you can declare variables with var, let, and const, write nested functions, and run code in a browser console or Node.js. It also builds on the previous chapters on global, function, and block scope. Here we connect those scopes into one structure, the scope chain, and follow exactly what the engine does when your code mentions a name.
The Working Model: Environments Linked Outward
Every time JavaScript enters a scope, it creates an environment record. This is a table that maps the names declared in that scope to their current values. A function call gets one, a block containing let or const gets one, a module gets one, and the global scope has one.
Each environment also holds a reference to its outer environment: the one that surrounds it in the source code. Following these outer references from the innermost scope out to the global scope gives you the scope chain.
When code uses a name, the engine resolves it like this:
- Look in the current environment record.
- If the name is not there, follow the outer reference and look again.
- Repeat until the name is found or the global environment has been checked.
- If the name is still not found, reading it throws a
ReferenceError.
The search stops at the first match. Scopes further out are never consulted, even if they declare the same name.
Walking the Chain Step by Step
Here is the basic case. inner has no level of its own, so the lookup moves outward.
const level = "global";
function outer() {
const level = "outer";
function inner() {
return level;
}
return inner();
}
console.log(outer()); // "outer"
console.log(level); // "global"Resolving level inside inner goes like this:
| Step | Environment checked | Has `level`? | Result |
|---|---|---|---|
| 1 | `inner` call | No | Move outward |
| 2 | `outer` call | Yes, `"outer"` | Stop and return `"outer"` |
| 3 | Global | Not checked | Never reached |
The global level still exists. The lookup simply found a closer one first. The next chapter covers this situation, called shadowing, in detail.
Chains can be longer, and blocks count as links:
const a = "A (global)";
function outer() {
const b = "B (outer)";
if (true) {
const c = "C (block)";
const inner = () => {
const d = "D (inner)";
return [d, c, b, a].join(" | ");
};
return inner();
}
}
console.log(outer());
// "D (inner) | C (block) | B (outer) | A (global)"From inside inner the chain is: inner → if block → outer → global. Each name is found at a different link. Built-ins like console and Math resolve the same way. They are found at the last link, the global environment.
Lexical, Not Dynamic: Where the Function Is Written
The outer reference is set when a function is created, based on where its code sits in the source. It does not depend on where the function is called. This is what "lexical scope" means in practice, and it is the most common source of wrong predictions.
const name = "global";
function show() {
return name;
}
function caller() {
const name = "caller";
return show();
}
console.log(caller()); // "global"show is called from inside caller, but show was written at the top level. Its outer environment is the global one, so caller's name is invisible to it. The call stack (who called whom) and the scope chain (who encloses whom) are separate structures.
The Chain Holds Bindings, Not Copies of Values
The chain links to environment records, and the records hold live bindings. A lookup reads the binding's value at the moment the lookup happens, not the value it had when the function was defined.
let greeting = "hello";
function speak() {
return greeting;
}
greeting = "goodbye";
console.log(speak()); // "goodbye"speak did not capture the string "hello". It holds a route to the greeting binding, and by the time it runs that binding contains "goodbye". This is the basis for the closure behavior covered in later chapters.
Assignment uses the same lookup. count = count + 1 inside a nested function updates whichever count binding the chain finds first, which may belong to an outer function.
function makeTally() {
let count = 0;
function bump() {
count = count + 1; // resolves to makeTally's count
}
bump();
bump();
return count;
}
console.log(makeTally()); // 2When the Chain Runs Out
If no environment declares the name, a read throws:
function readMissing() {
try {
return missingName;
} catch (e) {
return e.name;
}
}
console.log(readMissing()); // "ReferenceError"typeof is the one exception for reads: typeof missingName returns "undefined" instead of throwing. That only applies to names that are truly undeclared, as the temporal dead zone chapter shows.
A write to an unresolved name behaves differently. In sloppy (non-strict) mode, it silently creates a property on the global object. In strict mode, it throws. A later chapter on accidental globals covers this.
The Last Link: Two Kinds of Global Storage
The global environment is split into two parts:
- An object record backed by
globalThis(windowin browsers). Top-levelvarand function declarations in a classic script land here, alongside built-ins likeMath. - A declarative record for top-level
let,const, andclass. These are global names but not properties ofglobalThis.
Lookup checks the declarative part first, then the object part.
var viaVar = 1;
let viaLet = 2;
console.log(viaVar, viaLet); // 1 2
console.log(globalThis.viaVar); // 1
console.log(globalThis.viaLet); // undefinedGotchas That Break Static Lookup
Engines normally work out each name's location before the code runs, because the source text fixes the chain. Two legacy features break that:
with (obj) { ... }inserts an object into the chain, so a name may or may not resolve to a property depending on runtime data. It is a syntax error in strict mode.- Direct
eval("var x = 1")in sloppy mode can add a newvarto the surrounding function scope at runtime.
Both make code harder to read and slower to optimize. Avoid them. Strict mode, which ES modules and classes use automatically, removes the with problem and makes eval declarations stay inside their own scope.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Function reads an "unexpected" outer value | Expecting the caller's variables to be visible | Pass the value as a parameter. Lookup follows the definition site. |
| Value is newer than expected | The chain reads live bindings | Copy the value into a local `const` at the moment you need it frozen. |
| `ReferenceError: x is not defined` | No environment on the chain declares `x` | Declare it in a scope that encloses the use, or fix a typo. |
| Outer variable changed unexpectedly | An inner assignment resolved to an outer binding | Declare a local with `let` or `const` if you meant a new variable. |
| Global name missing from `globalThis` | Declared with `let`/`const`, or code runs as a module | Read it by name, or set `globalThis.name` explicitly if you really need it on the global object. |
Exercises
Exercise
What does this print, and why? const x = "global"; function a() { return x; } function b() { const x = "b"; return a(); } console.log(b());
Show answer
It prints "global". Function a was defined at the top level, so its outer environment is the global one. The lookup for x goes from a's environment straight to the global environment. b's local x sits on the call stack but not on a's scope chain.
Exercise
What does this print? let n = 1; function read() { return n; } n = 2; const first = read(); n = 3; console.log(first, read());
Show answer
It prints "2 3". read looks up the live binding n each time it runs. The first call happens when n is 2, and the second happens when n is 3.
Exercise
List the environments the engine checks, in order, when resolving total inside step, and say where the search stops. let total = 0; function run() { let total = 10; for (let i = 0; i < 1; i++) { const step = () => total + i; console.log(step()); } } run();
Show answer
The order is the step arrow function's environment (no total), then the for-loop iteration environment holding i (no total), then run's environment (total is 10, so the search stops there). The global total is never checked. It prints 10.