Behind the Scenes: JavaScript Code Execution
Tags: webdev, javascript, frontend, learning
Published: 2024-04-17 07:44:56

Ever found yourself in a late-night coding session, staring at your JavaScript code and wondering,_"What is going on here?"_ 🤷🏻‍♀️

Well, buckle up because we're about to take a ride through the execution context of JavaScript. Maybe not as exciting as binge-watching your favourite series, but trust me, it's important stuff 🤨! You might not know it, but there's a whole lot happening behind the scenes when you write a simple script.🤯

**Let's break down what an execution context is and why it’s important to know how it works in JavaScript.**


<br><br><br>


## Execution Context: What is it?
All JavaScript code needs an environment to run in, and typically that environment is a web browser. The browser’s JavaScript engine sets up a special environment to manage your code, known as an **`Execution Context`**. 
It's where all the action happens, as your code gets parsed, interpreted, and executed.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ol2deiz2abafie0o8kef.png)
**There are two types of execution contexts in JavaScript:**
1. Global Execution Context (GEC)
2. Function Execution Context (FEC)

## Global Execution Context (GEC)
When a JavaScript file is loaded, the engine first creates a default Execution Context called the **`Global Execution Context (GEC)`**. It's the top-level environment where global variables and functions live.

> **Note**: there can only be one per JavaScript file.

## Function Execution Context (FEC)
Every time you call a function, the JavaScript engine creates a Function Execution Context (FEC). This FEC lives inside the GEC, and it runs the function's code.

> **Note:** Since each function call creates its own FEC, you might end up with multiple FECs at runtime.

<br><br><br>


## Call Stack: The Execution Organizer
The Call Stack, also known as the Execution Stack, plays a key role in JavaScript's execution model. It keeps track of all the Execution Contexts created during the life cycle of a script. 

It follows a Last In, First Out (LIFO) structure, meaning the most recently called function is executed first and removed from the stack when it finishes. 

This stack-based execution model allows JavaScript to manage function calls, returns, and the flow of control within a script.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/duprbrvr96h7jwovtqlg.png)

## Creation of Execution Contexts
Now, let's talk about how these `execution contexts (GEC or FEC)` are created. 
**It happens in two phases:**
1. **Creation Phase**
2. **Execution Phase**


## 1️⃣ Creation Phase (Memory Phase)
In this phase, variables and functions are declared in memory but not yet initialized. The Execution Context Object holds important data for the code in the Execution Context during its run-time.

**The creation phase includes 3 stages:**
1. Creation of the Variable Object (VO)
2. Creation of the Scope Chain
3. Setting the value of the `this` keyword

### <u>**Creation Phase:**</u> Creation of the Variable Object (VO)

The `Variable Object (VO)` is an object-like container created within an Execution Context. It stores the variables and function declarations defined within that Execution Context in the **<u>_Memory Component as shown below in the diagram_</u>**

- Variables declared with **`var`** are set to 'undefined' in the VO.
- Function declarations are added to the VO and stored in memory, making them accessible even before the code starts running.
    

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ccai63br1o9mdi28sd1e.png)

> This process of storing variables and function declaration in memory prior to the execution of the code is known as `Hoisting`. 


### <u>**Creation Phase:**</u>  **Creation of The Scope Chain**

**In FEC,** Each Function Execution Context creates its scope: the space/environment where the variables and functions it defined can be accessed via a process called Scoping.

When a function is defined inside another function, the inner function can access the outer function's code and even the scope of its parent functions. This hierarchy of scopes is known as **`lexical scoping`**.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/whaker3a5qozx1fs16pm.png)

> This concept of scope brings up an associate phenomenon in JavaScript called `closures`. 


### **<u>Creation Phase:</u> Setting The Value of The "this" Keyword**

The JavaScript `**this**` keyword refers to the scope where an Execution Context belongs.

- In the **Global Execution Context (GEC)**, the **`this`** keyword refers to the global object, which in a web browser is the **`window`** object.
- In the **Function Execution Context (FEC)**, the **`this`** keyword points to the context where the function is called. This depends on how the function is invoked.

These stages set the foundation for code execution in JavaScript by properly organizing the context's memory, scope, and references.

## 2️⃣ Execution Phase
_**This is where the real work gets done.** _
After the creation phase, the execution phase begins.Up until now, the VO contained variables set to **`undefined`**.

Now, the JavaScript engine reads the code again, updates the all the variable with the actual values, and then the code is executed.

## **<u>Let's Put It All Together</u>**
To understand how this all plays out, consider the following example:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jqbpvp00r2vtzyx9gvdy.png)

**Here's how the execution context unfolds step by step in your JavaScript code:**


### **➡️ Step 1: Global Execution Context (GEC)**

**Phase 1 : Memory Creation Phase**:

- **`var n = 5`** declaration creates a variable **`n`** with an initial value of `**undefined**` .
- **`function square(n)`** declaration creates the function **`square` .**
- **`showsquare`** declaration creates a variable with an initial value of **`undefined`**.

**Phase 2 : Execution Phase**:

- **`n`** assigned the value 5.
- **`var square1 = square(n)`** is evaluated. This calls the function **`square`** with the argument **`n`** (which has a value of **`5`**). The Call Stack is used to create a new Function Execution Context (FEC) for the **`square`** function.





### **➡️ Step 2: Function Execution Context (FEC)**

**Phase 1 :  Memory Creation Phase**:

- In the **`square`** function, the parameter **`n`** is created and assigned the value of **`5`** (the argument passed in).
- The variable **`ans`** is created and initialized to **`undefined`**.

**Phase 2 :  Execution Phase**:

- The expression **`n * n`** is calculated, resulting in **`5 * 5 = 25`**.
- The variable **`ans`** is assigned the value of **`25`**.
- The **`square`** function returns the value **`25`** and its Function Execution Context is popped off the Call Stack.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v51bu4tkwtq5z7gn58hi.png)

### **➡️ Step 3: Return to Global Execution Context**

- The returned value **`25`** from the **`square`** function is assigned to the **`showsquare`** variable in the Global Execution Context.
- The **`console.log(showsquare)`** statement is executed, printing the value **`25`** to the console.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b40qq8qu8p5tibn58rnf.png)

By following these steps, the JavaScript engine processes the code in terms of creating and executing the necessary execution contexts for both the global and function scopes.

**And there you have it! By understanding how execution contexts work, you gain insight into how JavaScript processes your code.👩🏻‍💻**

Thanks for Reading! 😃

Connect with Me! 🙋🏻‍♀️
If you enjoyed this journey through JavaScript execution contexts, be sure to check out my [website](https://shreyajoshi.tech/) for more tech insights. I am also on [Instagram](https://www.instagram.com/codebyshreya/) and [LinkedIn](https://www.linkedin.com/in/codebyshreya/) for more updates. 

And if you want to keep everything neat and tidy, [Linktree](https://linktr.ee/codebyshreya) might just be your new best friend.

Happy Coding! 🎉