JavaScript Execution Context & Call Stack
What is Execution Context?
An Execution Context is an environment where JavaScript code is evaluated and executed.
Types of Execution Contexts:
1. Global Execution Context (GEC)
- Created by default when a JavaScript file runs.
- this refers to the global object (window in browser).
2. Function Execution Context (FEC)
- Created when a function is invoked.
- Each function gets its own context.
3. Eval Execution Context (rarely used)
- Created by eval() (not recommended).
Phases of Execution Context
Each Execution Context goes through two phases:
1. Creation Phase
- Memory is allocated for variables and functions.
- var is initialized as undefined.
- let and const are placed in the Temporal Dead Zone (TDZ).
- Functions are hoisted.
2. Execution Phase
- Code runs line-by-line.
- Variables are assigned values.
- Functions are invoked.
Example
var a = 2;
function greet() {
console.log("Hello, World!");
}
greet();
What happens:
1. Creation Phase:
- a → undefined
- greet → function reference
2. Execution Phase:
- a → 2
- greet() → creates a new function execution context
JavaScript Call Stack
The Call Stack is a mechanism that tracks function calls in the order they are called.
How it works:
1. Code starts in the Global Execution Context → pushed onto the stack.
2. When a function is called → a new Function Execution Context is pushed.
3. When a function finishes → its context is popped off the stack.
Call Stack Example
function one() {
two();
}
function two() {
three();
}
function three() {
console.log("End");
}
one();
Stack Flow:
Call Stack:
-> Global()
-> one()
-> two()
-> three()
-> console.log("End")
Then the stack unwinds:
<-three()
<-two()
<-one()
<-Global()
Output
Output: End
Common Error: Stack Overflow
function repeat() {
repeat();
}
repeat(); // RangeError: Maximum call stack size exceeded
This happens when functions call themselves infinitely without a base condition.