Sub topic 2
Lexical Scope: Where Code Is Written Decides What It Sees
This chapter assumes you can declare and call functions, know the difference between var, let, and const at a basic level, and have passed a function as an argument before. You also need the idea from the previous chapter that functions are values: they can be stored in variables, returned, and handed to other code.
Closures rest on one rule. A function can see the variables that surround it in the source code. Who calls it, and from where, does not change that. This rule is called lexical scope. Once you can read it from the code, most closure behavior becomes predictable.
What Scope Means
A scope is the region of a program where a name, such as a variable, function, or parameter, can be used. Outside that region the name either refers to something else or does not exist at all.
JavaScript creates a new scope for each function body and, with let and const, for each block. The next chapter covers the difference between block and function scope. Here the question is simpler: when a function uses a name, how does JavaScript decide which declaration that name refers to?
"Lexical" means "relating to the text". In a lexically scoped language, you answer that question by reading the source. Look at where the function is written, then look outward through the code that surrounds it.
The Core Rule in One Example
const x = 'global';
function outer() {
const x = 'outer';
function inner() {
return x;
}
return inner;
}
const fn = outer();
console.log(fn()); // 'outer'fn() runs at the top level of the program, where x is 'global'. It still returns 'outer'. The reason is that inner is written inside outer, and the nearest x in the code around inner is the one declared in outer. The place where fn() is called has no effect on that lookup.
This example also shows something that later chapters will explain in detail: outer has already returned when fn() runs, yet its x is still available. For now, the point is which x gets used, and the answer comes from the text.
Scopes Nest Like Boxes
Each function or block written inside another creates a scope inside the outer one. Code can look outward through every enclosing scope. It can never look into a scope nested inside it, or into a sibling scope next to it.
When inner uses x, JavaScript checks inner's own scope first. It finds nothing there, moves out to outer's scope, and finds x = 'outer'. The search stops at the first match. A later chapter on the scope chain walks through this lookup step by step. For this chapter, remember the direction of the search: from the inside out, following the nesting in the source.
The Caller Does Not Matter
A common wrong model is to think a function can see the variables of whatever function called it. Here is a test of that idea:
function logLevel() {
return level;
}
function run() {
const level = 'debug';
return logLevel();
}
try {
run();
} catch (err) {
console.log(err.message); // level is not defined
}logLevel is called from inside run, while run's level exists. It still throws a ReferenceError. logLevel is written at the top level, and nothing at the top level declares level. The call site gives it nothing.
The fix is to pass the value in explicitly or to write the function where the value is in scope:
function logLevel(level) {
return level;
}
function run() {
const level = 'debug';
return logLevel(level);
}
console.log(run()); // 'debug'Lexical Versus Dynamic Scope
Some languages use dynamic scope, where a name is resolved by walking the chain of active calls at runtime. Bash's local variables behave this way:
x=global
show() { echo "$x"; }
caller() { local x=caller; show; }
caller # prints: caller
show # prints: globalIn Bash, show sees caller's x because caller is on the call stack when show runs. The equivalent JavaScript would print global both times.
| Question | Lexical scope (JavaScript) | Dynamic scope (Bash `local`) |
|---|---|---|
| When is a name resolved to a declaration? | Fixed by the source text | Decided at runtime by the call stack |
| Does the caller's local variable leak in? | No | Yes |
| Can you predict lookups by reading one function and its surroundings? | Yes | No, you must know every possible caller |
| Effect of passing a function elsewhere | It keeps seeing its original surroundings | It sees whatever is active where it runs |
This difference is what makes closures useful. A function you return, store, or pass as a callback keeps its connection to the variables written around it, no matter where it eventually runs.
Shadowing
When an inner scope declares a name that already exists in an outer scope, the inner declaration shadows the outer one. Inside the inner scope the outer variable cannot be reached by that name.
const name = 'module';
function greet() {
const name = 'function';
if (true) {
const name = 'block';
console.log(name); // 'block'
}
console.log(name); // 'function'
}
greet();
console.log(name); // 'module'All three variables exist at the same time. Each console.log uses the nearest declaration in the text around it. Shadowing is legal and sometimes intentional, but accidental shadowing causes real bugs. A frequent case is a callback parameter that reuses an outer name:
const items = ['a', 'b'];
const result = [];
items.forEach((items) => {
// 'items' here is the current element, not the array
result.push(items.toUpperCase());
});
console.log(result); // ['A', 'B']The code works, but anyone reading the callback has to work out that items means a single string. If the callback later needs the whole array, the outer items is out of reach. Linters such as ESLint have a no-shadow rule that flags this.
The last point surprises people:
const value = 'outer';
function read() {
try {
console.log(value); // throws: value is in the temporal dead zone
} catch (err) {
console.log(err.name); // 'ReferenceError'
}
const value = 'inner';
return value;
}
console.log(read()); // 'inner'The inner const value belongs to the whole function body from the start, so the lookup stops there even before the declaration line runs. This shows that scope is decided by the structure of the code, not by which lines have run so far.
Edge Cases That Bend the Rule
A few features make scope harder to read from the source, or behave in ways that seem to break the rule.
new Function(...)builds a function from a string. Its body is always scoped to the global scope, not to the place where it was created.evalin sloppy mode can add new variables to the surrounding function's scope at runtime. In strict mode (including ES modules and classes) it gets its own scope instead.withputs an object's properties into scope, so whether a name means a variable or a property depends on runtime data. It is forbidden in strict mode.
function test() {
const secret = 'local';
const viaArrow = () => typeof secret;
const viaConstructor = new Function('return typeof secret;');
return [viaArrow(), viaConstructor()];
}
console.log(test()); // ['string', 'undefined']The arrow function is written inside test, so it sees secret. The Function constructor's body is not, so secret does not exist for it. This is assuming no global variable named secret.
Reading Scope Correctly: A Checklist
When you need to know what a name refers to:
- Find the function or block where the name is used.
- Look for a declaration of that name in that scope:
let,const,var, a parameter, a function declaration, or a class. - If none exists, move to the scope that encloses it in the source, and repeat.
- If you reach the global scope with no match, reading the name throws a
ReferenceError. - Ignore the call site completely.
Exercise
What does this program print, and why? const color = 'red'; function paint() { return color; } function scene() { const color = 'blue'; return paint(); } console.log(scene());
Show answer
It prints 'red'. paint is written at the top level, so its color lookup goes from paint's scope to the global scope and finds 'red'. The color declared inside scene is not in any scope that encloses paint's source, so calling paint from scene has no effect.
Exercise
A teammate writes function handler() { return userId; } at the top of a file and calls it inside function onLogin() { const userId = 42; return handler(); }. It throws "userId is not defined". Give two ways to fix it.
Show answer
Either pass the value as an argument (function handler(userId) { return userId; } and call handler(userId)), or define handler inside onLogin so userId is in an enclosing scope in the source. The second option makes handler a closure over onLogin's variable.
Exercise
Inside a function, a line logs total and then two lines later the code declares let total = 0;. An outer total = 10 exists. What happens on the logging line?
Show answer
It throws a ReferenceError. The inner let total belongs to the whole function scope, so it shadows the outer total from the start of the function. Before its declaration runs it is in the temporal dead zone, and the lookup does not fall back to the outer variable.