Sub topic 5
Lexical Environments Under the Hood
This chapter assumes you can read nested functions, know how let, const, and var differ in scope, and have followed the previous chapter on how the scope chain resolves variables. Here we look at the structure the JavaScript engine uses to make that chain work. The ECMAScript specification calls it a lexical environment.
The Two Parts of a Lexical Environment
A lexical environment is an internal object with two parts:
- An environment record, which stores the bindings (variable names and their current values) declared in that scope.
- An outer reference, which points to the lexical environment of the enclosing scope. The global environment's outer reference is
null.
Variable lookup follows these links. The engine checks the current record first. If the name is not there, it follows the outer reference and checks again, and it keeps going until it finds the name or reaches null. If it reaches null, it throws a ReferenceError.
Execution Contexts
An execution context is the engine's record of the code that is running right now. Each function call creates a new execution context and pushes it onto the call stack. When the call returns, its context is popped off.
Each execution context points to a lexical environment. A function call creates a fresh environment for that call's parameters and local variables. Blocks such as if bodies and loop bodies also get their own environment when they declare let or const bindings.
How a Function Knows Its Outer Scope
When the engine creates a function object, it stores a reference to the lexical environment that is current at that moment. The specification names this hidden slot [[Environment]]. You cannot read the slot from your code, but it decides the outcome of every lookup.
When you later call the function, the engine builds the new call environment and sets its outer reference to the function's [[Environment]]. The caller's environment plays no part in this. That is why lexical scope depends on where a function is written and not on where it is called.
const site = 'global';
function outer() {
const site = 'outer';
function inner() {
// inner's [[Environment]] was set to outer's call environment
return site;
}
return inner;
}
function caller() {
const site = 'caller';
const fn = outer();
return fn(); // the caller's environment is not consulted
}
console.log(caller()); // 'outer'When inner() runs, its environment record is empty, so the lookup for site moves to its outer reference. That reference is outer's call environment, where site is 'outer'.
Environments Can Outlive Their Call
outer has already returned when inner runs, and its execution context is gone from the call stack. Its lexical environment survives because inner's [[Environment]] slot still refers to it. The garbage collector frees an environment only when nothing refers to it anymore. The next chapter builds the definition of a closure on this behavior.
| Structure | Created when | Holds | Lifetime |
|---|---|---|---|
| Execution context | A function is called | The running code and its current environment | Until the call returns |
| Lexical environment | A call starts or a block runs | Bindings and an outer reference | Until nothing refers to it |
| `[[Environment]]` slot | A function object is created | A reference to the current environment | As long as the function exists |
Exercise
In the code below, what does run() log, and which environment supplies the value? let level = 1; function make() { let level = 2; return () => level; } function run() { let level = 3; const f = make(); console.log(f()); }
Show answer
It logs 2. The arrow function was created during the make() call, so its [[Environment]] points to make's call environment, where level is 2. The lookup never reaches run's environment because run is not on the arrow function's chain of outer references.
Exercise
Why does make's environment still exist after make() returns?
Show answer
The returned function's [[Environment]] slot still refers to it. The garbage collector can free an environment only after nothing refers to it.