JavaScript execution context defines how and where code is evaluated and executed. Every time JavaScript runs a script, a function, or a block, it creates an execution context to manage variables, scope, and this binding.
Types of Execution Context
JavaScript has three main execution contexts:
1. Global Execution Context (GEC)
- Created when the JavaScript file is loaded
- Only one global context exists per program
- Creates:
- Global object (
windowin browsers,globalin Node.js) thiskeyword- Global variables and functions
- Global object (
Example:
var x = 10;
function test() {
console.log(x);
}
Here, x and test() belong to the global execution context.
2. Function Execution Context (FEC)
- Created every time a function is invoked
- Each function call gets its own execution context
- Contains:
- Arguments object
- Local variables
- Function scope
thisvalue
Example:
function add(a, b) {
var sum = a + b;
return sum;
}
add(2, 3);
Calling add() creates a new function execution context.
3. Eval Execution Context (Rare)
- Created when
eval()executes code - Avoided in production due to security and performance issues
Phases of Execution Context
Each execution context is created in two phases:
1. Memory Creation Phase (Hoisting Phase)
- Variables are allocated memory and set to
undefined - Functions are stored entirely in memory
thisis initialized
Example:
console.log(a); // undefined
sayHi(); // works
var a = 5;
function sayHi() {
console.log("Hi");
}
2. Execution Phase
- Code is executed line by line
- Variables get assigned actual values
- Functions are executed when invoked
Execution Context Stack (Call Stack)
JavaScript uses a stack structure to manage execution contexts.
How it works:
- Global Execution Context is pushed first
- Function call creates a new context and pushes it
- Function completes → context is popped
- Control returns to the previous context
Example:
function one() {
two();
}
function two() {
console.log("Hello");
}
one();
Call stack order:
- Global → one() → two()
Relation with Scope and Closures
Execution context defines:
- Variable environment
- Lexical scope
Closures work because inner functions retain access to the lexical environment of their execution context even after the outer function finishes execution.
Common Interview Points
- Execution context is created before code execution
- Functions are fully hoisted, variables are partially hoisted
- Call stack controls execution order
- Each function call creates a new execution context
Summary
- Execution context manages code execution
- Three types: Global, Function, Eval
- Two phases: Memory creation and Execution
- Call stack tracks execution contexts
Understanding execution context is critical for debugging, closures, hoisting, and asynchronous JavaScript behavior.

