Sub topic 4
How the Scope Chain Resolves Variables
This chapter assumes you can declare functions, nest one function inside another, and tell var, let, and const apart. It also builds on the earlier idea that scope is fixed by where code is written.
The Lookup Rule
When JavaScript meets a variable name, it has to find which declaration that name refers to. It searches in a fixed order:
- The current scope (the block or function that is running).
- The scope that encloses it in the source code.
- Each enclosing scope after that, moving outward.
- The global scope.
The search stops at the first match. If no scope declares the name, reading it throws a ReferenceError. This series of nested scopes is called the scope chain.
const site = 'global site';
const theme = 'light';
function page() {
const theme = 'dark';
function widget() {
const size = 'small';
return `${size} ${theme} ${site}`;
}
return widget();
}
console.log(page()); // 'small dark global site'Inside widget, the engine finds size locally. It finds theme one level out, in page. It finds site in the global scope. The global theme is never reached, because the lookup stopped at page.
Lookup Only Goes Outward
The chain has one direction. An inner function can see its outer variables, but an outer function cannot see inner ones.
function outer() {
function inner() {
const secret = 42;
}
inner();
return typeof secret; // 'undefined': secret is not visible here
}
console.log(outer());typeof is used here because it does not throw on undeclared names. A plain console.log(secret) inside outer would throw a ReferenceError.
Shadowing
When an inner scope declares a name that already exists further out, the inner declaration shadows the outer one. Inside that scope the outer variable cannot be reached by name. That is why widget saw 'dark' and not 'light'.
Common Errors
Shadowing Plus the Temporal Dead Zone
A let or const declaration shadows the outer name for its whole block, including the lines before the declaration. Those earlier lines are the temporal dead zone.
const level = 'outer';
function check() {
console.log(level); // ReferenceError: Cannot access 'level' before initialization
const level = 'inner';
}
check();The lookup finds the local level first and stops there, so it never falls back to the outer value.
Accidental Globals
In non-strict code, assigning to a name that no scope declares creates a new global variable without any error. Strict mode throws instead:
'use strict';
function setTotal() {
totl = 10; // typo for "total"
}
setTotal(); // ReferenceError: totl is not definedSummary
| Situation | Result |
|---|---|
| Name declared in current scope | Local variable used |
| Name declared only in an outer scope | Nearest outer declaration used |
| Same name at several levels | Innermost one wins (shadowing) |
| Name read before its local `let`/`const` | `ReferenceError` (temporal dead zone) |
| Name declared nowhere | `ReferenceError` on read |
Exercise
What does this code log, and why? const a = 1; function f() { const a = 2; function g() { return a + b; } const b = 3; return g(); } console.log(f());
Show answer
It logs 5. Inside g, the name a is found in f's scope, where it is 2, and this shadows the global a. The name b is also found in f's scope, where it is 3. By the time g() runs, b has been initialized, so there is no temporal dead zone error. 2 + 3 = 5.
Exercise
Inside a nested function you write console.log(count), and count exists only in the global scope. A later line in that same nested function declares let count = 0. What happens and how do you fix it?
Show answer
It throws a ReferenceError. The local let declaration shadows the global count for the whole function, and the log runs before that declaration, inside the temporal dead zone. Fix it by renaming the local variable, or by moving the log after the declaration if you meant to log the local value.