JavaScript Behind The Scenes: The Execution Context & Call Stack
Tags: javascript, beginners, webdev
Published: 2021-07-25 18:09:32

Hey fellow developers, in the last blog, we learnt about [**The JavaScript Engine & The Runtime**](https://dev.to/bhattpawan/discovering-javascript-the-javascript-engine-runtime-5hia) . The topic for today will be **The Execution Context and Call Stack**. So without much of an ado, lets begin.

## What is an Execution Context?
Execution Context is an environment that executes our JavaScript Code. In addition to this, it also stores all the necessary information that is needed for execution like the variable names or the argument names passed to a function. 
*"Everything in JavaScript happens inside the Execution Context"*

### Execution Context made easy....
To understand Execution Context in a better way, let us take an example of us ordering a burger from our favorite store. So, when we get our burger, we get the following things:
* Burger (of course)
* The Polybag / Paperbag (containing our order)
* Ketchup, Tissues, Fries, Cola and other add-ons, which enhance our burger eating experience.

So considering our order, we can draw the following comparisons:
* Burger -> Our JavaScript Code
* The Polybag / Paperbag -> Execution Context 
* Ketchup, Tissues, Fries etc -> The functions, variables or arguments passed to the function which help/enhance our JavaScript code execution.

Here is an illustration for the same:
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1627029139394/0p5ZR0kUv.png)

### What's inside an Execution Context?
An Execution Context primarily consists of:
* Variable Environment: The variable environment consists of the following:
 * let, const and var declarations
 * functions
* Scope Chain (will be covered later)
* this keyword (will be covered later)

So, for now, lets just forget that we know anything like the scope chain & this keyword (we'll cover it later, don't worry), and focus on the variable environment.

If we consider code example below:

```
const name = 'Hello World';

function sayHello(){
console.log('Hello People');
}
```
The Execution Context will look like:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8wx71tja8u6wctwqv7n.png)
Before moving on to how the JavaScript code is executed, let us have a look at what the **Call Stack** is.
## The Call Stack:
The Call Stack is a place that stacks execution context on top of each other in order to keep track of the execution order. The Execution Contexts are processed in  LIFO manner i.e., Last-In-First-Out.
Here is an illustration:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1cvfer1foy0yllfl218l.png)
## How is the code **actually** Executed?
So now that we are aware of the terminologies, let us see how our code gets executed. Take the following code snippet for instance:
```
const name = 'Pawan';

function sum(a, b){
let s = a + b;
return s;
}
const getSum = sum(2, 3);
``` 
The code execution takes place mainly in two phases:
1. **The Creation Phase:** In which the variables, functions are declared in the variable environment.
2. **The Execution Phase:** In which the code is executed.

**1. The Creation Phase**
During the creation phase, the variables and functions defined in global scope are allocated memory and assigned an initial value. For the code snippet above, the global execution context in creation phase will look like.
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dubi9peyuif0yq6kqcp4.png)  
 
**2. The Execution Phase:**
During the execution phase, the variables are assigned values and the code is executed *one-line-at-a-time*. The execution context changes as follows:
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7ezf22j5djzpq88wqgek.png)
 
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yo7orefrwqp4ic71py20.png)

So now you must be thinking, for multiple functions we would have hundreds of execution contexts, so how would JavaScript track its execution? The answer is **The Call Stack**. Below is how the call stack will be populated for our code:

* When the code is run for the first time, the call stack looks like:
**Creation Phase**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g0u4b2ge5vesxxdoa9ug.png)
**Execution Phase**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e459ehu5ec5jxq8lju3a.png)

* When the function, sum gets called, it gets its own execution context and now our call stack looks like:

**Creation Phase:**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nppdqxfcgy6jy2iwi7wb.png)
**Execution Phase:**
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1xb07bmcceiesog2f4kx.png)

* Now that our function execution context has completed its execution, it gets removed from the call stack ( for now lets suppose that it does) and our getSum variable gets populated. So now our call stack will be:
  
![image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bv930yuett697aj6bky7.png)

After our global execution context is done executing all the statements, it will just remain like that waiting for any explicit calls/instructions including the click events or hover events etc. The execution context remains active so long as our browser window is active.

So, I hope I was able to explain how the Execution Context and the Call Stack works together to execute our JavaScript code. To summarize it:
* Execution Context executes the JavaScript code.
* Call Stack maintains a stack of execution contexts to maintain an order of execution.

That's all for now. Any queries and recommendations can be posted in the comment box below.

Stay Safe & Happy Learning 🙌.