What actually happens when JavaScript executes a function?
Trace execution from the call site through execution contexts, lexical environments, and the call stack.
When one function calls another, JavaScript needs to remember where to return when the inner function finishes. It does that with the call stack. An execution context holds the information needed while a piece of code runs, including its local bindings and the value of this where applicable.
When one function calls another, JavaScript needs to remember where to return when the inner function finishes. It does that with the call stack. An execution context holds the information needed while a piece of code runs, including its local bindings and the value of this where applicable.
The quick version
A function call creates an execution context, establishes its environment and this binding, then evaluates its body. The engine tracks active calls on the execution stack; returning or throwing removes the current frame.
Build the mental model
The useful mental model is not “JavaScript runs line by line” but “each call temporarily adds a frame with access to an environment chain.” Lexical scope is determined by where functions are defined, while the call stack records how execution arrived there. Those are separate structures.
See it in code
const label = 'outer';
function makeReader() {
const label = 'inner';
return function read() {
return label;
};
}
const read = makeReader();
read(); // "inner"
makeReader has returned, so its stack frame is gone. Its lexical environment remains reachable through read’s closure.
Where it gets tricky
A thrown exception unwinds active frames until a matching handler is found; a frame does not remain suspended just because a callback still references one of its bindings. Async functions split execution across turns: the function returns a promise, and continuation after await is scheduled later. Keep the stack model separate from the event-loop model when debugging traces.
A common misunderstanding
A closure is not a frozen copy of local variables, and the lexical environment is not the call stack.
What this changes in an application
This distinction explains closures, recursion, stack overflows, debugging frames, and why deeply recursive synchronous work can block the main thread.
Questions worth exploring next
- How does recursion consume stack space?
- What changes when a function is async?
References and next steps
- JavaScript execution model — primary or authoritative documentation for the underlying behavior.
- MDN Web Docs — use the relevant API reference for adjacent browser details.