JavaScript Execution Context
Have you ever wondered how JavaScript works?
JavaScript is a synchronous, single-threaded language, meaning it executes one line of code at a time in a specific order. It can only proceed to the next line once the current line has finished executing.
When JavaScript code runs, an global execution context is created. This happens in two phases:
- Memory Creation Phase — Allocates memory for variables and functions.
- Code Execution Phase — Executes the code line by line.
Example of an Execution Context:
we will refer this code throughout the article
var a = 10;
function square ( num ){
var answer = num * num ;
return answer ;
}
var square1 = square(a);
var square2 = square(5);
Execution Context Breakdown
Whenever JavaScript runs this code, it creates an execution context that consists of two phases:
1. Memory Creation Phase
a
is declared and initialised toundefined
.square
function is stored in memory (entire function body).
After the memory phase, JavaScript knows:
a -> undefined
square -> function reference
2. Code Execution Phase
a = 10
→ Assigns10
toa
.- The function
square(num)
is not executed yet, soans
is not created.
What Happens When We Call square(5)
?
var square2 = square(5);
A new Execution Context (EC) is created for square(5)
, which follows the same two-phase process:
Execution Context for square(5)
- Memory Creation Phase
num -> undefined
ans -> undefined
- Code Execution Phase
num = 5
ans = 5 * 5 = 25
- The function returns 25, and this execution context is popped off the stack.
Now, let's visualize how JavaScript handles this:
Step 1: Global Execution Context (GEC) Creation
Memory Phase
Code Execution Phase
a = 10
✅ (Updated)- Function
square(num)
is defined but not executed yet. result = square(5);
→ Callssquare(5)
, creating a new Execution Context (EC).
Step 2: Execution Context (EC) for square(5)
A new FEC is created and pushed onto the Call Stack.
Code Execution Phase
num = 5
✅ans = 5 * 5 = 25
✅- Return
25
to the caller.
Execution Context is Popped from the Stack.
Step 3: Back to Global Execution Context
result = 25
✅console.log(result);
prints25
✅- Global Execution Context is popped, and the program finishes.
If you find this post helpful, please consider buying me a coffee! ☕