Understanding execution contexts is fundamental to understanding scope, hoisting, closures, and the this keyword.
What is an Execution Context?
Every time JavaScript runs code, it creates an execution context — an environment that contains all the information needed to execute that code.
Types of Execution Contexts
- Global Execution Context: Created when the script first runs. One per program.
- Function Execution Context: Created each time a function is called.
- Eval Execution Context: Created by eval() (don't use eval).
Creation Phase vs Execution Phase
console.log(x); // undefined (not ReferenceError!)
console.log(y); // ReferenceError: Cannot access before initialization
var x = 5;
let y = 10;
// Creation Phase:
// 1. var x → initialized to undefined (hoisting)
// 2. let y → in Temporal Dead Zone (TDZ)
// 3. Function declarations → fully hoisted
// Execution Phase:
// 1. console.log(x) → undefined
// 2. console.log(y) → ReferenceError (still in TDZ)
// 3. x = 5
// 4. y = 10The Call Stack
function third() { console.log("third"); }
function second() { third(); }
function first() { second(); }
first();
// Call Stack visualization:
// | |
// | third() | ← currently executing
// | second() |
// | first() |
// | global |
// |___________|Stack Overflow
// Infinite recursion → stack overflow
function infinite() {
infinite(); // Each call adds to the stack
}
infinite(); // RangeError: Maximum call stack size exceeded
// Fix: use tail recursion or iteration
function factorial(n, acc = 1) {
if (n <= 1) return acc;
return factorial(n - 1, n * acc); // Tail position
}Variable Environment
// Each execution context has its own variable environment
function outer() {
const a = 1; // outer's variable environment
function inner() {
const b = 2; // inner's variable environment
console.log(a + b); // Scope chain: inner → outer → global
}
inner();
}This Binding
Each execution context also determines the value of this:
- Global context: this = window (browser) or global (Node)
- Function call: this = window (sloppy) or undefined (strict)
- Method call: this = the object
- Constructor: this = new object
- Arrow function: this = enclosing context (lexical)