An Execution Context is the environment where JavaScript code is evaluated and executed.
Think of it as a box that contains everything needed to run your code:
variables, functions, scope, and this.
✅ There Are 3 Types of Execution Contexts
1. Global Execution Context (GEC)
- Created when the JS file first loads
- Creates the global object (
windowin browser,globalin Node) thisrefers to the global object- Only one GEC exists
2. Function Execution Context (FEC)
- Created each time a function is called
- Has its own variables, arguments, and
this - Multiple FECs can exist stacked together
3. Eval Execution Context (rarely used)
Created inside the eval() function.
✅ What Happens When an Execution Context Is Created?
Each context has two phases:
🔵 1. Creation Phase (Memory Allocation)
JavaScript sets up:
✔ Variable Environment
- Memory is allocated
varvariables get undefinedlet/constvariables are placed in the Temporal Dead Zone (TDZ)
✔ Function declarations
- Fully hoisted with their bodies
✔ Scope chain
- Determines variable access
✔ this binding
🔴 2. Execution Phase
- JS executes code line by line
- Assigns values
- Runs functions
- Executes expressions
🧪 Example to Understand Execution Context
var x = 10;
function add(a, b) {
let c = a + b;
return c;
}
add(5, 3);
Execution Flow:
1. Global Execution Context Created
- Memory allocated
x = undefinedadd = function() { ... }
Then execution:
x = 10add(5, 3)→ creates new Function Execution Context
2. Function Execution Context Created (for add)
Creation Phase:
a = 5b = 3c = TDZ
Execution Phase:
c = a + b→8- return
8 - FEC destroyed after function ends
⭐ Execution Context vs Call Stack
Execution contexts are placed on the Call Stack.
Example call stack:
| add() Context |
| Global Context (GEC) |
-------------------------
As functions finish, their contexts are removed (popped).
🎯 Short Interview Answer
The Execution Context is the environment in which JavaScript code runs.
It is created in two phases—creation (memory allocation, hoisting, scope chain, this binding) and execution (code runs line-by-line).
There are two main types: Global Execution Context and Function Execution Context.
These contexts are managed through the call stack.