DEV Community

Cover image for JavaScript Execution Context – How JS Code Runs Behind the Scenes
Jamir Hossain
Jamir Hossain

Posted on

JavaScript Execution Context – How JS Code Runs Behind the Scenes

Before understanding what JavaScript Execution Context is, we need to know how and in which environments we can run JavaScript code.

First of all, we can run JavaScript in two environments:

  1. Through the Browser
  2. Through the Node.js

How does JavaScript code run on our computer?

When we write JavaScript code on our computer and then try to run it, the code first goes to either the Browser or Node.js.

However, the JavaScript code we write is not directly understood by the Browser or Node.js. At this point, both send the code to the JavaScript Engine built into them. There are different types of engines, for example:

  1. V8 Engine in Google Chrome,
  2. SpiderMonkey in Mozilla Firefox,
  3. V8 Engine in Node.js, etc.

Next, the JavaScript Engine compiles the JavaScript code into machine code. This machine code is then sent to the computer, which executes it, and we see the output displayed.

As programmers, we need to have a good understanding of this intermediate step, i.e., how the JavaScript Engine compiles JavaScript code into machine code.

So, now we need to understand how the JavaScript Engine works. The JavaScript Engine works in two ways to convert code into machine code. First one is Interpretation and the second one is Compilation. So, what are Interpretation and Compilation?

What is Interpretation, and How Does it Work?

Interpretation is the process of reading all the source code written in a high-level language line by line and converting each line into machine code immediately after reading it. If there is an error while reading a line of code, the process stops right there, making it easy for the programmer to identify the error. This makes debugging straightforward. However, since this process reads the code line by line, it is comparatively slower.

What is Compilation, and How Does it Work?

Compilation is the process of converting all the source code written in a high-level language into machine code at once. In this case, even if there are errors in the code, it will still compile and only show errors at runtime. As a result, it becomes harder for the programmer to identify the errors, making debugging more challenging. However, since the entire source code is converted into machine code at once, this process is comparatively faster. So now, the question arises: Is JavaScript a compiled or an interpreted language?

Is JavaScript a Compiled or an Interpreted Language?

Initially, JavaScript was primarily considered an interpreted language. However, since this process was quite slow, modern JavaScript engines began using a new technique that combines both interpretation and compilation, known as Just-In-Time (JIT) Compilation. This process combines interpretation and compilation to convert code into machine code. As a result, it is much faster and easier to debug compared to older methods.

To understand how JavaScript’s Just-In-Time (JIT) Compilation works, we need to understand JavaScript’s Execution Context. Let’s now try to understand JavaScript’s Execution Context.

JavaScript Execution Context

First, take a look at the following code example.

Code Example

var a = 1;

function one() {
  console.log(a);

  function two() {
    console.log(b);

    var b = 2;

    function three(c) {
      console.log(a + b + c);
    }

    three(4);
  }

  two();
}

one();
Enter fullscreen mode Exit fullscreen mode

Output

1
undefined
7
Enter fullscreen mode Exit fullscreen mode

When we ran the code, we tried to print the b variable before it was declared inside the two() function, and the output was undefined. However, no error occurred. The question arises: how did the b variable have the value undefined? The answer lies in the JavaScript Execution Context. Now, we will explore JavaScript Execution Context in more detail.

There are two types of Execution Context in JavaScript:

  1. Global Execution Context
  2. Function Execution Context

Each Execution Context goes through two phases: Creation Phase and Execution Phase.

Global Execution Context

When we run JavaScript code, the first thing that happens is the Global Execution Context. This context first goes through its Creation Phase, where several things happen:

Creation Phase

  1. A Global Object is created.
  2. A this object is created and assigned the value of the Global Object.
  3. A Variable Object is created, where all functions and variables are declared. The variables are assigned undefined as their value, and the functions are assigned references to their respective functions.

Once the Creation Phase completes, the Global Execution Context moves to the next phase: Execution Phase, where more steps occur.

Execution Phase

  1. The variables that were declared in the Creation Phase and initialized with undefined are now assigned their respective values.
  2. The functions declared in the Creation Phase, which were stored as references, are now called and executed.

Function Execution Context

When the functions referenced during the Execution Phase of the Global Execution Context are called, each function creates its own Function Execution Context. Just like the Global Execution Context, the Function Execution Context also goes through a Creation Phase, where several steps occur:

Creation Phase

  1. A parameter object is created for the function.
  2. A this object is created and assigned the value of the Global Object.
  3. A Variable Object is created, where all functions and variables are declared. The variables are assigned undefined as their value, and the functions are assigned references to their respective functions.

Once the Creation Phase is completed, the Function Execution Context moves to the Execution Phase, where more steps occur.

Execution Phase

  1. The variables declared in the Creation Phase, which were initialized with undefined, are now assigned their respective values.
  2. The functions declared in the Creation Phase are now called and executed.

Function Execution Context in Nested Functions

When functions are called within other functions, a new Function Execution Context is created for each of these functions. Each Function Execution Context then goes through both the Creation Phase and Execution Phase. This process continues for each function called inside another function, and each function will go through these phases separately.

Let's look at the diagram below.

Image description

We have seen that both the Global Execution Context and Function Execution Context go through certain steps. The only difference is that, in the Global Execution Context, the first step is to create the global object, whereas, in the Function Execution Context, the first step is to create a parameter object for the function.

Now, the question arises: how does JavaScript manage these Execution Contexts when they are created for both the global context and each function?

Managing Execution Contexts with the Execution Stack

To manage these contexts, JavaScript uses a data structure called the Execution Stack. The Execution Stack stores contexts in a stack-like manner: first, the Global Execution Context, followed by each Function Execution Context. When all the execution contexts are stored in the stack, JavaScript processes them one by one, starting from the top of the stack.

Scoping with let and const

It is important to note that when we declare variables with let or const inside a global or function scope, these variables are not stored in the Variable Object during the Creation Phase, and they are not initialized with undefined. Instead, these variables are directly declared and assigned their values in the Execution Phase.

Consider the following code example:

Code Example

function two() {
  console.log(b);

  const b = 2;
}

two();
Enter fullscreen mode Exit fullscreen mode

If we run this code, we will encounter a ReferenceError. This is because we are trying to print the value of the b variable before declaring it, and since b is declared using const, it behaves differently from regular variables. Variables declared with const or let are not stored in the Variable Object during the Creation Phase, which is why we get an error when trying to access them before they are assigned a value.

Conclusion

I hope this explanation of how JavaScript works and what happens during its Execution Context phases has provided you with a clearer understanding. In the next lesson, we will explore another JavaScript topic.

You can connect with me on GitHub and Linkedin.

Top comments (0)