Skip to content

How JS works behind the scenes

Posted on:October 6, 2023 at 05:15 AM

To know behind the scenes how JavaScript code gets executed internally, we have to know something called Execution Context and its role in the execution of JavaScript code.

Execution context represents an environment in which JavaScript code runs. It has two components,

The Memory Component is the part where all the variables and function declarations are stored as a key: value pair and the Code component parses the code line by line. It is also known as the Thread of execution.

Execution Context

Inside the execution context, JS code is executed in two phases.

Let us Understand this with the help of the following code:

var num1 = 5;
var num2 = 2;
function sum(n1, n2) {
  return n1 + n2;
}
var newSum = sum(num1, num2);

Creation phase

The following things happen in this phase:

Creation Phase

Execution Phase

The following happens in this phase:

Execution Phase

Execution Phase

Execution Phase


Call Stack

To keep track of all the execution contexts, the JavaScript engine uses Call stack also known as Runtime Stack or Machine Stack.

The call stack is a data structure that stores the current state of your program, including the location of each function call. It uses the Last In First Out principle. Each time a function is called, the JavaScript engine pushes a new entry onto the top of the call stack. When the function returns, the JavaScript engine pops the top entry off the call stack.

Here’s an example of how the call stack works in JavaScript:

function firstFunction() {
  secondFunction();
}

function secondFunction() {
  thirdFunction();
}

function thirdFunction() {
  return "something";
}

firstFunction();

In this example, when the firstFunction is called, it calls secondFunction, which in turn calls thirdFunction. The JavaScript engine maintains a call stack that looks like this:

Call stack

When thirdFunction returns, the JavaScript engine pops it off the call stack, leaving:

Call stack

When secondFunction returns, the JavaScript engine pops it off the call stack, leaving:

Call stack

Thus when a function completes its execution, its context is removed from the call stack, and control returns to the previous context. This process continues until all contexts are executed.