Execution Context and Call Stack
Execution Context and Call Stack
The fundamental environment where JavaScript code is evaluated and executed.
The Chef and the Recipe Card Stack
JavaScript manages function calls using a Call Stack following LIFO (Last In, First Out). Each function call spawns an isolated Execution Context with its own variable environment and "this" binding.
Global Execution Context (GEC) Creation
Created by default before any code runs. It sets up the global object (`window` in browsers, `global` in Node) and initializes the `this` binding to the global object.
Phase 1: Memory Creation Phase
The engine scans code: variable declarations (`var`) are allocated with initial value `undefined`, function declarations are stored in their entirety, and `let`/`const` are allocated in the TDZ.
Phase 2: Code Execution Phase
The engine processes code line by line, assigns real values to variables, evaluates expressions, and executes function invocations.
Function Execution Context (FEC)
Every time a function is invoked, a new FEC is pushed onto the Call Stack. It contains local variables, arguments, and outer lexical environment references.
Popping and Stack Teardown
When a function returns or completes, its FEC is popped off the Call Stack, restoring the execution state of the calling context.
Tracing how contexts are pushed and popped from the call stack:
function first() {
console.log("Entering first()");
second();
console.log("Exiting first()");
}
function second() {
console.log("Inside second()");
}
first();
Entering first()
Inside second()
Exiting first()
Stack Overflow via Unbounded Recursion
The Risk: Calling a recursive function without a proper base case fills the Call Stack until the browser throws `RangeError: Maximum call stack size exceeded`.
The Fix: Always ensure recursive functions have a verified termination base case, or refactor to an iterative loop or trampolining.
- ✓ Two phases per context: 1. Creation Phase (memory allocation) → 2. Execution Phase (line-by-line run).
- ✓ Call Stack works on LIFO (Last In, First Out).
- ✓ GEC is created once when the program boots; FEC is created on every function invocation.
- ✓ Each FEC manages: Variable Environment, Lexical Environment, and "this" binding.
- ✓ Stack Overflow occurs when stack limit (~10,000 frames) is exceeded.