JavaScript Execution Context

Varun Wadhwa
3 min readFeb 12, 2025

--

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:

  1. Memory Creation Phase — Allocates memory for variables and functions.
  2. 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 to undefined.
  • 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 → Assigns 10 to a.
  • The function square(num) is not executed yet, so ans 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)

  1. Memory Creation Phase
  • num -> undefined
  • ans -> undefined
  1. 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

  1. a = 10 ✅ (Updated)
  2. Function square(num) is defined but not executed yet.
  3. result = square(5); → Calls square(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

  1. num = 5
  2. ans = 5 * 5 = 25
  3. Return 25 to the caller.

Execution Context is Popped from the Stack.

Step 3: Back to Global Execution Context

  • result = 25
  • console.log(result); prints 25
  • Global Execution Context is popped, and the program finishes.

If you find this post helpful, please consider buying me a coffee! ☕

Buy me a coffee

--

--

Varun Wadhwa
Varun Wadhwa

Written by Varun Wadhwa

I have post graduate in MCA having 6 plus years of experience in web development

No responses yet