Sub topic 4
How the Scope Chain Resolves Variables
This chapter assumes you can write and call functions, you know how var, let, and const differ, and you have read the earlier chapters on lexical scope and on block versus function scope. Here we look at the lookup itself: what JavaScript does, step by step, when your code uses a name like total or user.
The Scope Chain in One Sentence
The scope chain is the ordered list of scopes JavaScript searches to find a variable. The search starts in the current scope and moves outward one level at a time until it reaches the global scope. The first scope that has a binding for the name wins. If no scope has one, the lookup fails.
Each scope has a link to its parent scope, which is the scope where its code was written. Those links form the chain. Because the links are fixed when the code is written, the chain for a given function never depends on who calls it.
Walking the Chain
Here is a three-level example. Each level declares some names, and some of those names are declared again further in.
const a = 'global a';
const b = 'global b';
function outer() {
const b = 'outer b';
const c = 'outer c';
function inner() {
const c = 'inner c';
console.log(a, b, c);
}
inner();
}
outer(); // global a outer b inner cWhen inner runs, JavaScript resolves each name on its own:
cis found ininner's own scope, so the search stops there.bis not ininner, so the search moves toouterand finds'outer b'.ais in neither function, so the search reaches the global scope.
The search only ever goes outward. An outer scope can never see the variables of a scope nested inside it, because nothing links a parent to its children.
Shadowing
When an inner scope declares a name that an outer scope also declares, the inner one shadows the outer one. Shadowing means the outer binding is hidden from that point inward. In the example above, inner's c shadows outer's c, and outer's b shadows the global b.
Shadowing does not change the outer variable. Both bindings exist side by side, and code at each level sees the nearest one.
Function parameters count as declarations in the function's scope, so they shadow too:
const value = 10;
function show(value) {
return value;
}
console.log(show(3)); // 3
console.log(value); // 10Reading Versus Writing Through the Chain
Lookup works the same way whether you read a variable or assign to it. An assignment without a declaration walks the chain and updates the first binding it finds.
let count = 0;
function increment() {
count += 1; // no declaration here, so this updates the outer count
}
increment();
increment();
console.log(count); // 2This is how an inner function changes state that belongs to an outer scope. If you add let in front of count inside increment, you create a new local variable that shadows the outer one. Then count += 1 throws, because the local count is read before it has a value. The next section explains why.
When the Nearest Binding Is Not Ready Yet
Shadowing takes effect for the whole scope, not just from the line where the declaration appears. A let or const binding exists from the start of its block, but it cannot be used until its declaration line runs. The span before that line is called the temporal dead zone (TDZ).
The rule that matters for lookup: if the name is found in the current scope but is still in the TDZ, the search does not continue outward. It throws.
const name = 'global';
function greet() {
try {
console.log(name); // finds the local name, which is still in the TDZ
} catch (err) {
console.log(err.name, '-', err.message);
}
const name = 'local';
console.log(name);
}
greet();
// ReferenceError - Cannot access 'name' before initialization
// localMany developers expect the first console.log to print 'global'. It cannot, because the local name already shadows the global one for the whole function body.
var behaves differently. A var declaration is hoisted and set to undefined at the start of the function, so the lookup finds it and returns undefined without throwing:
var label = 'global';
function show() {
console.log(label); // undefined, not 'global'
var label = 'local';
}
show();When the Lookup Fails
If the search reaches the global scope and still finds nothing, what happens next depends on whether you are reading or writing, and whether the code runs in strict mode.
| Situation | Sloppy mode | Strict mode |
|---|---|---|
| Read an undeclared name | `ReferenceError` | `ReferenceError` |
| `typeof` an undeclared name | `'undefined'` | `'undefined'` |
| Assign to an undeclared name | Creates a global property | `ReferenceError` |
| Read a `let`/`const` in its TDZ | `ReferenceError` | `ReferenceError` |
| Read a hoisted `var` before its line | `undefined` | `undefined` |
The sloppy-mode assignment row causes many bugs. A typo or a missing let silently creates a global variable:
function setTotal() {
totl = 42; // typo: meant "total"
}
setTotal();
console.log(globalThis.totl); // 42 in sloppy modeIn strict mode the same code throws ReferenceError: totl is not defined. ES modules and class bodies are always strict. Classic scripts and CommonJS files in Node.js are sloppy unless they start with 'use strict';.
The End of the Chain: The Global Scope
The global scope is the last link, and it has two parts that lookup checks as one:
- An object part, which is
globalThis(windowin browsers). Top-levelvardeclarations and function declarations in a classic script become properties of this object. - A declarative part, which holds top-level
let,const, andclassdeclarations. These are global variables, but they are not properties ofglobalThis.
var fromVar = 1;
let fromLet = 2;
console.log(globalThis.fromVar); // 1 (in a classic script)
console.log(globalThis.fromLet); // undefined
console.log(fromLet); // 2, found by normal lookupIn an ES module, top-level declarations of any kind live in the module's own scope. That scope sits between your code and the global scope, so nothing you declare at module top level becomes a property of globalThis.
The Chain Is Fixed Where the Function Is Written
The previous chapter showed that scope is lexical. For lookup, this means the chain a function uses comes from where the function was defined. It does not come from the code that calls it:
const level = 'global';
function report() {
return level;
}
function caller() {
const level = 'caller';
return report();
}
console.log(caller()); // 'global'report's parent scope is the global scope, so caller's local level is never on its chain. This fixed link from a function to its defining scope is what the next chapters build on. When a function outlives the scope that created it, it still holds that link.
Performance Notes
Engines such as V8 resolve most variable references when they compile the code. They do not search scope by scope at run time, so a deep chain costs little in practice. Two features defeat this: direct eval and the with statement, because they can add names to a scope while the code runs. Both are discouraged, and strict mode bans with entirely. Write code for clarity, not to shorten scope chains.
Common Errors at a Glance
- Expecting an outer value to show through before a local
letorconstdeclaration. The TDZ blocks the lookup. - Writing
x = 5inside a function and expecting a new local variable. In sloppy mode it either changes an outerxor creates a global. - Assuming a callee can see the caller's local variables. Lookup follows where code was written, not the call stack.
- Expecting top-level
letandconstto appear onwindoworglobalThis.
Exercise
What does this code print, and why? const msg = 'outer'; function test() { if (true) { console.log(msg); let msg = 'inner'; } } test();
Show answer
It throws "ReferenceError: Cannot access 'msg' before initialization". The let msg inside the if block shadows the outer msg for the whole block. When console.log(msg) runs, lookup finds the block's msg while it is still in the temporal dead zone, so it throws instead of moving outward to 'outer'.
Exercise
In a classic script without 'use strict', what are the values of result and globalThis.counter after this runs?
function bump() {
counter = (typeof counter === 'undefined' ? 0 : counter) + 1;
return counter;
}
bump();
const result = bump();
Show answer
Both are 2. counter is never declared, so typeof counter returns 'undefined' on the first call instead of throwing, and the assignment creates a global property counter set to 1. The second call finds that global through the scope chain and sets it to 2. In strict mode, the first assignment would throw a ReferenceError.
Exercise
Given the code below, which value does each call return? const tag = 'A'; function makeReader() { const tag = 'B'; return function read() { return tag; }; } function run(reader) { const tag = 'C'; return reader(); } console.log(run(makeReader()));
Show answer
It prints 'B'. read was defined inside makeReader, so its chain runs read → makeReader → global. Lookup finds tag in makeReader's scope. The tag inside run is on the call stack but not on read's scope chain, so it is never consulted.