Sub topic 5
Lexical Environments Under the Hood
This chapter assumes you already know how lexical scope works, how let, const, and var differ in scope, and how the scope chain finds a variable by searching outward. Here you will look at the machinery the JavaScript specification uses to make those rules work. That machinery is the lexical environment. Closures are built directly on it, so a clear picture of it makes the next chapter much easier.
Two Structures: Execution Contexts and Lexical Environments
When JavaScript runs code, it keeps track of two related but separate things.
An execution context is the bookkeeping for code that is currently running. Every function call creates one, and the engine pushes it onto the call stack. When the function returns, its execution context is popped off and discarded.
A lexical environment is the structure that stores variables. It has two parts:
- An environment record, which maps names to values (for example,
count → 0). - An outer reference, which points to the lexical environment that encloses this one. The global environment's outer reference is
null.
An execution context points to the lexical environment it is currently using, but the two do not share a lifetime. The context goes away when the call ends. The environment can stay alive afterward if something still refers to it. That gap between the two lifetimes is what makes closures possible.
| Structure | Holds | Created when | Discarded when |
|---|---|---|---|
| Execution context | Which code is running, the current environment, the value of `this` | A script starts or a function is called | The code finishes running |
| Lexical environment | Variable bindings plus an outer reference | A script, function call, or block is entered | Nothing references it any more (garbage collection) |
The Hidden Link: A Function's [[Environment]]
The spec gives every function object an internal slot called [[Environment]]. When a function is created, the engine stores a reference to the lexical environment that is current at that moment. It does not record where the function is later called.
When the function is called, the engine:
- Creates a new execution context and pushes it on the call stack.
- Creates a new lexical environment for the call.
- Sets that environment's outer reference to the function's
[[Environment]]. - Adds the parameters and local declarations to the new environment record.
- Runs the body.
Step 3 explains the behavior you saw with lexical scope. The outer reference comes from where the function was defined, never from the caller. The scope chain is just this list of outer references, followed one link at a time.
Here is the code that produces those environments:
function outer() {
const x = 1;
function inner() {
const y = 2;
return x + y; // y found in inner's record, x found one link out
}
return inner();
}
const result = outer();
console.log(result); // 3The Creation Phase: Why Hoisting and the TDZ Exist
The engine does not fill an environment record line by line as the code runs. When it enters a function, it first scans the body and creates a binding for every declaration. Only after that does it run any statements. The three kinds of declaration start in different states:
varbindings are created and set toundefinedstraight away.- Function declarations are created and set to the full function object straight away.
let,const, andclassbindings are created but left uninitialized. Reading one before its declaration line runs throws aReferenceError. The span between entering the scope and reaching the declaration is the temporal dead zone (TDZ).
function showCreationPhase() {
console.log(typeof helper); // 'function': already initialized
console.log(v); // undefined: created, set to undefined
try {
console.log(l);
} catch (e) {
console.log(e.name); // 'ReferenceError': binding exists but is in the TDZ
}
var v = 1;
let l = 2;
function helper() {}
}
showCreationPhase();The TDZ shows that the binding for l already exists in the record. If it did not, the lookup would continue to the outer environment and might find an outer l instead. That behavior is called shadowing, and it applies from the first line of the scope, before the declaration runs.
const name = 'global';
function shadow() {
try {
console.log(name); // does NOT print 'global'
} catch (e) {
console.log(e.name); // 'ReferenceError'
}
const name = 'local';
}
shadow();Block Environments
Functions are not the only thing that creates environments. Each time execution enters a block ({ ... }, a for body, an if branch) that contains let, const, or class declarations, the engine creates a new declarative environment. Its outer reference points to the environment that was current before the block. var declarations skip block environments and go into the nearest function's (or the global) record. That is the mechanism behind block scope versus function scope.
function blocks() {
var a = 'function-level';
let b = 'function-level';
{
var a = 'still function-level'; // same binding as above
let b = 'block-level'; // new binding in a new block environment
console.log(a, b); // 'still function-level' 'block-level'
}
console.log(a, b); // 'still function-level' 'function-level'
}
blocks();A for (let ...) loop goes one step further and creates a fresh environment for every iteration, copying the loop variable forward each time. A later chapter on the loop bug relies on this detail.
The Global Environment Is Special
The global lexical environment has a split record:
- An object record backed by the global object (
globalThis). Top-levelvarand function declarations in a classic script become properties here. - A declarative record for top-level
let,const, andclass. These are global variables, but they are not properties ofglobalThis.
var g1 = 'from var';
let g2 = 'from let';
console.log(globalThis.g1); // 'from var'
console.log(globalThis.g2); // undefined
console.log(g2); // 'from let'Every Call Gets Its Own Environment
Each call creates a new environment, even when you call the same function again. Recursion works because of this: every level has its own n.
function countdown(n) {
if (n === 0) return [];
const rest = countdown(n - 1); // a new environment with its own n
return [n, ...rest];
}
console.log(countdown(3)); // [3, 2, 1]This also tells you what happens when a function is created inside another function's call. The inner function's [[Environment]] points at that particular call's environment. If you call the outer function twice, you get two separate environments and two inner functions, each linked to its own one. When the outer call returns, its execution context is popped, but its environment survives as long as an inner function still holds a reference to it. The next chapter puts the name "closure" to this.
How Real Engines Optimize This
The specification describes a model that behaves as if every environment were a heap object with a chain of links. Engines such as V8 keep the visible behavior identical but implement it more cheaply:
- Stack allocation for uncaptured variables. If no inner function refers to a variable, the engine can keep it in a register or on the stack and throw it away when the call returns.
- Heap contexts for captured variables. Variables that some inner function uses are moved into a heap-allocated "context" object, so they can outlive the call.
- Shared contexts. All inner functions created in the same scope usually share one context object. If one closure uses a large variable, it can keep that value alive for its siblings too. The memory chapter returns to this.
- Deoptimization with
evalandwith. Directevalcan read any name at runtime, so the engine has to keep every variable in scope reachable. This blocks many of the optimizations above.
You can see these environments in browser DevTools. Pause on a breakpoint inside a nested function and look at the Scope panel. It lists Local, Closure, Script, and Global sections, which correspond to the chain of environments. The Closure section shows only the captured variables, which confirms the optimization described above.
Exercise
In the code below, what does each console.log print, and why? let total = 10; function report() { console.log(total); } function run() { let total = 99; report(); } run();
Show answer
It prints 10. The report function was created at the top level, so its [[Environment]] points to the global environment. When run() calls it, the new environment for report's call gets its outer reference from report's [[Environment]], not from run's environment, so the lookup for total skips run's total = 99 and finds the global total = 10.
Exercise
Why does this throw a ReferenceError instead of logging 'outer'? let label = 'outer'; { console.log(label); let label = 'inner'; }
Show answer
Entering the block creates a new block environment, and during the creation phase the engine adds an uninitialized binding for label to it. The lookup for label stops at this binding, which is still in the temporal dead zone, so reading it throws. The outer label is shadowed for the whole block, not just from the declaration line onward.
Exercise
A function f is called three times. How many lexical environments are created for f's calls, and what decides whether any of them survive after f returns?
Show answer
Three, one per call. Each one becomes unreachable and can be garbage collected when its call ends, unless some value still references it, typically an inner function created during that call whose [[Environment]] slot points to it and which was returned or stored somewhere.