JavaScript Execution Context

In JavaScript, everything happens within an execution context. JavaScript is a synchronous, single-threaded language, meaning it executes code one line at a time in a sequential manner.

Components of the Execution Context

JavaScript’s execution context consists of two main components:

  1. Memory Component

    • Stores variables, objects, and functions as key-value pairs.
  2. Code Component

    • Executes code line by line.
Execution Context

What Happens When You Run a JavaScript Program?

When you run a JavaScript program, an execution context is created. The execution context handles both the memory setup and the code execution.

How JavaScript Code is Executed

Consider the following JavaScript code:

var n = 2;

function square(num) {
  var ans = num * num;
  return ans;
}

var square2 = square(n);
var square4 = square(4);

Global Execution Context

When this code is executed, a global execution context is created with two phases:

1. Memory Creation Phase

  • During this phase, memory is allocated for all variables and functions.
  • Variables like n, square2, and square4 are initially set to undefined.
  • The function square is stored as a whole function.
Memory Creation Phase

Code Execution Phase

After the memory is set up, the code is executed line by line:

  1. Line 1: n = 2
  2. Line 8: A new execution context is created for the function square(2):
    • Memory is assigned to the parameters num and ans.
    • Code execution calculates ans = 4.
    • The result 4 is returned, and the execution context is destroyed.
  3. Line 9: Another execution context is created for square(4):
    • Memory is assigned to num and ans again.
    • Code execution calculates ans = 16.
    • The result 16 is returned, and the execution context is destroyed.

How Does JavaScript Manage Multiple Execution Contexts?

When there are nested function calls, JavaScript manages execution contexts through a call stack. This stack keeps track of the order of execution contexts, ensuring the correct context is called after the current one is completed.

For the code above, the call stack would look like this during execution:

Execution callstack