Sub topic 2
Lexical Scope: Where Code Is Written Decides What It Sees
This chapter assumes you can declare and call functions, declare variables with let and const, and return a function from another function. The previous chapter showed that functions are values. This chapter explains which variables a function can see.
The rule
A scope is the region of code where a variable name is available. JavaScript uses lexical scope. This means the position of a function in the source code decides which outer variables it can read. Where the function is later called has no effect.
The engine works out this nesting before any code runs. If you read the code and see which braces each function sits inside, you can tell which variables that function can reach.
A worked example
const x = 'global';
function outer() {
const x = 'outer';
function inner() {
return x;
}
return inner;
}
const fn = outer();
console.log(fn()); // 'outer'inner is written inside outer, so its x refers to the x declared in outer. The call fn() runs at the top level, where a different x holds 'global'. That does not change the result, because the call site plays no part in resolving x.
Call site does not matter
To see the rule more clearly, call a function from inside another function that declares the same name:
const label = 'module';
function show() {
return label;
}
function caller() {
const label = 'caller';
return show();
}
console.log(caller()); // 'module'show is defined at the top level. It reads the top-level label, even though caller has its own label when the call happens. Some languages use dynamic scope, where the caller's variables would be visible to the function it calls. JavaScript does not work that way.
Common errors
| Mistake | What actually happens |
|---|---|
| Expecting a function to see variables from the function that calls it | It sees only variables from the places it is written inside |
| Assuming an inner variable leaks outward | Outer code cannot read variables declared inside a nested function |
| Thinking that reassigning a name in the caller changes what a callee reads | The callee reads its own lexically enclosing variable |
Exercise
What does this code log, and why? const color = 'red'; function paint() { return color; } function scene() { const color = 'blue'; return paint(); } console.log(scene());
Show answer
It logs 'red'. The function paint is written at the top level, so color inside paint refers to the top-level color. The color declared inside scene is not visible to paint, because JavaScript resolves names by where a function is written, not by where it is called.
Exercise
Change the code from the previous exercise so that scene() returns 'blue'. You may not change the value of either variable.
Show answer
Move paint inside scene, so that its enclosing scope is scene: function scene() { const color = 'blue'; function paint() { return color; } return paint(); }. Now the nearest color that encloses paint in the source code is 'blue'.