How Javascript code Executes!😳
Tags: javascript, webdev, frontend, beginners
Published: 2023-05-16 07:49:52

---
title: How Javascript code Executes!😳
published: true
series: Javascript core concepts
date: 2023-05-05 10:06:18 UTC
tags: #javascript #webdev #frontend #beginners
canonical_url: 
---


## Understanding the Code Execution Phases in JavaScript

Javascript is a single-threaded programming language used to create dynamic and interactive web pages. Understanding how Javascript code is executed is important to optimise code performance and avoid errors. In this article, we'll go through the step-by-step execution of Javascript code, including the different code execution phases.

Javascript code is executed in two main phases:

1. **Compilation Phase**

2. **Execution Phase**

## **Compilation Phase**

In the Compilation Phase, the Javascript engine reads the code and checks for syntax errors. It then creates a compiled version of the code called an **Abstract Syntax Tree** (AST). This **AST** represents the structure of the code in memory and is used during the Execution Phase. Let us see what this AST looks like for the following code:

```javascript
function add(num1, num2) {
  return num1 + num2;
}

```

First, the Javascript engine will check for any errors in the code. If it comes across some error then it will stop the compilation and throws the error right there on the code console. If not then it will create an AST. The AST for this code would look roughly like this:

```javascript
Program
  FunctionDeclaration
    Identifier: add
    FunctionExpression
      Identifier: null
      Params
        Identifier: num1
        Identifier: num2
      Body
        ReturnStatement
          BinaryExpression
            Identifier: num1
            Identifier: num2

```

Hope you get the idea here of how the above code is read by the Javascript engine. Now let's go to the next phase ie, the **Execution Phase.**

## **Execution Phase**

In the Execution Phase, the Javascript engine executes the code line by line. During this phase, it creates a **Global Execution Context** and then a new **Execution Context for**  **each**  **function call**. These Execution Contexts are added to the **Execution Stack,** which is a **Last In First Out (LIFO)** data structure. Let's see these terms in detail.

**<mark>Note</mark>** <mark>: </mark> **<mark>Execution Stack </mark>** <mark>is also known by other names such as </mark> **<mark>Call Stack, Execution Context Stack, Program Stack, Control Stack, Runtime Stack, and Machine Stack</mark>** <mark>.</mark>

### **Execution Context**

An execution context is a container that holds information about the environment in which a piece of Javascript code is executed. It includes information such as the value of the `this` keyword, the variables that are defined within the function, and the scope chain.

There are three types of execution contexts in Javascript:

- **Global Execution Context**

- **Function Execution Context**

- **Eval Function Execution Context**

We will mainly look into the **Global Execution Context** and **Function Execution Context.**

### **<mark>Global Execution Context</mark>**

The global execution context is created when a code is executed, and it is the default execution context that goes into the Execution stack. The global execution context includes **global variables** and **functions** that are accessible from anywhere in the code. The global execution context is created before any code is executed, and it is destroyed when the script finishes executing.

### **<mark>Function Execution Context</mark>**

The function execution context is created when a function is called. Each time a function is called, a new function execution context is created. The function execution context includes the variables and parameters defined within the function, which are accessible to any nested functions. When a function finishes executing, its execution context is destroyed.

Now, let's understand how the execution stack looks like for the following code using a visual diagram:

```javascript
1 function add(a, b) {
2 return a + b;
3 }

4 var result = add(2, 3);

```

![example](https://cdn.hashnode.com/res/hashnode/image/upload/v1683277716262/940abf29-83dc-413b-878b-5723842a5685.jpeg)

<mark>Note: When the execution context is created, the variables are stored in the memory and the value assigned to it as </mark> `undefined` <mark>at that moment. </mark> **<mark>Functions</mark>** <mark>are stored as it is in the memory during the memory phase.</mark>

**step 1:** As in the diagram you can see that global execution context comes into the stack and stores `result = undefined` in the memory. Also, the `add()` function is in the global context, it will also be stored in the memory.

**step 2:** `add(2, 3)` on line no. 4 is executed. This will create a separate function execution context which will now be pushed into the stack for the execution of `add(2,3)`.

**setp3:** `add(2,3)` is executed in its function execution context and gives the output as `5`. After execution of `add(2,3)` its function execution context pops out of the stack.

**setp4:** `result` variable stores `5`.

**setp5:** Global execution context pops out of the stack as all the code is executed successfully.

## Summary

We have seen the 2 main phases of the Javascript engine which are essential in running the code. Also, we have seen the execution flow in detail with the sample code example and a visual diagram. By knowing how Javascript works inside the memory, one can easily debug and understand other core concepts which can help in mastering Javascript as a whole.