JavaScript Lexical Lookup Across Function Calls
Quick answer
Free identifiers in a function resolve through the environments associated with its definition, not the local variables of its caller.
How it works
When a function executes, its local parameters and declarations establish local bindings. If a name is absent locally, lookup follows the outer environment chain. A call stack records active calls; it is not the lexical lookup chain. A function can be passed elsewhere without changing its outer environment.
const rate = 2;function quote(n) { return n * rate; }function run() { const rate = 9; return quote(3); }console.log(run());Expected output in Node.js:
6quote resolves rate where it was defined.
function outer(x) { function read(y) { return x + y; } return read(4); }console.log(outer(5));Expected output in Node.js:
9read finds x in its outer function and y in its own parameters.
Common mistakes
Do not confuse the caller’s local variables with the function’s lexical environment.
Practice
Draw the lookup path for x and y in the second example.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Lexical Lookup Across Function Calls — Knowledge Check
Apply the taught concept and predict the output.
Which environment determines a free identifier in quote above?
What does the call stack track?
What changes when the same function is passed to another caller?
What is the exact console output in JavaScript Lexical Lookup Across Function Calls example 1?
const rate = 2;function quote(n) { return n * rate; }function run() { const rate = 9; return quote(3); }console.log(run());What is the exact console output in JavaScript Lexical Lookup Across Function Calls example 2?
function outer(x) { function read(y) { return x + y; } return read(4); }console.log(outer(5));