What is Execution context
Tags: javascript, codenewbie, writing, webdev
Published: 2021-05-14 03:24:04


Things to know or be aware of before diving into execution context.

JavaScript is the language of the browsers. It has the following characteristics:-

* JavaScript is a single thread language. This means that javaScript engine reads and runs the code one line at a time. And it reads the code from top to bottom and from left to right just like how you read a book in English.

* JavaScript is synchronous for the most part. This means that it works in sequence. It waits for each line to run and complete before it can move on to the next.

With these in mind let’s get into execution context.

**What is execution context?**

Execution context is a conceptual description of the environment in which codes are run, read and executed by JavaScript engine. It comprise of memory & the thread of execution. There are three types of execution context. These are:-

* Global execution context
    * This is the default or base execution context when the file loads in the browser. There is only one global context and all the codes outside of the functions within are in the global context. It is within the window object.

* Function execution context
    * This is the execution context created when functions are invoked or called upon during the execution phase.

* Eval execution context
    * This is the execution context created inside eval functions.

<u>How is the execution context created?</u>

The execution context is created in two phases. These are the creation and execution phase.

**<u>Creation phase</u>**

During the creation phase the Js engine only reads the code and sets up the variable environment, lexical environment and the value of this(keyword) as it goes through the thread of execution.

During this phase the following happens:-
1. It parses the code line by line & identifies variable and function declarations
2. It stores the variable and function declaration identifiers in live memory
3. If the variable is declared with var it will be assigned the value of undefined and function declaration will be assigned function definition
4. If the variable is declared with let and const then it won’t get assigned any value but will be stored in live memory/variable environment 
5. If the function gets invoked or called it will create a local execution context in which it goes through the same process
6. The value of this(keyword) gets assigned  

```javascript
var totalDistance = 26.2;
function runningMiles (age){
       const runningDistance = age*2
       return runningDistance
}
const runnerName = "Denis"

```
So the JS engine parses the code line by line and stores the variable identifiers totalDistance & runnerName as well as function runningMiles in live memory. This is what results in hoisting. A situation in which 
>the variable and function declarations are put into memory during the compile phase, but stay exactly where you typed them in your code.

It then assigns totalDistance the value of undefined since it was declared with var. And function definition was assigned to function runningMiles while variable runnerName is left uninitialized during creation or compiling phase. This is because variables declared with let and const don't get assigned values or get initialized until the execution phase. That is the reason why we are able to access or reference variable declaration with var & function declarations before initialization or execution.

The variable runnerName was declared with const so does not have a value assigned to it during this phase.The variable runnerName will only be initialized in execution phase unlike totalDistance that was declared with var. This is why if we try to access it, Js will throw the following error.![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fry0dcfbe16x5dpm5ebd.png)This means you can't access runnerName or any variable declared with either let or const before JS engine evaluates it at the line it was declared. This is what is called <mark>"Temporal Dead Zone"</mark>. 
> let variables cannot be read/written until they have been fully initialized, which happens when they are declared (if no initial value is specified on declaration, the variable is initialized with a value of undefined). Accessing the variable before the initialization results in a ReferenceError.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ll4kbfl3jze391ah1eoi.png)The JS engine did not get inside the function because it was not invoked or called. As a result local execution context was not created which means the code is only being run in the Global execution context as you can see above.

**<u>Execution phase</u>**

In execution phase Js engine execute the code line by line assigning values to variables and executing function calls. 

During this phase the following happens:-

1. The Js engine will look for the value of variables inside the variable environment & then the lexical environment up in the scope chain and resolve them
2. When it gets to a line where a  function is invoked it creates a local execution context for that function & that function gets pushed onto the <mark>call stack</mark> 
3. It then gets inside the local function and starts executing the code line by line
4. If it finds another call to a function, it will pause on that line & create a local execution context for that function & that function gets pushed up the call stack
5. If there is no other function called inside that local context it’s currently in, then it will go ahead & execute all the code inside the function on top of the call stack first and keep going down until it gets to the global context at the bottom. So it executes with <mark>last one in first order</mark>.  
6. The function gets executed and resolved with a return value and get popped off the call stack
7. If the return is not written explicitly then it will return undefined for the function
8. And the JS engine goes back where it left off  and execute the rest of the codes in the  local context it is in
9. It keeps the process down the call stack until all codes are executed and resolved including the ones in the global context

This is what happens in the execution phase using the same example above.![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p6d8p1jy9layfbg0663o.png)Js engine executed the code line by line & resolved the values of variable identifiers. 

Let's see what happens when the function above is invoked or called.
```javascript
var totalDistance = 26.2;
function runningMiles (age){
       const runningDistance = age*2
       return runningDistance
}
const runnerName = "Denis"
const output = runningMiles (18)
```
<u>Creation phase</u>
![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ppdde9il30ac1lbeljt2.png)

During the creation phase the JS engine will parse the code line by line. It will store variables totalDistance, runningMiles and runnerName in the live Memory. The JS engine will assign undefined for totalDistance. And assign function definition for runningMiles while runnerName & output are left uninitialized. But when the JS engine reaches output it will pause where it is at and create a local execution context. It will then store variables age & runningDistance in the local memory. Both will not get initialized with a value during this phase.

<u>Execution phase</u>

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/k2hvwmhra8bsa9ei7c7s.png) 

The Js engine will then start evaluating variables and resolving the variables age & runningDistance in the local memory. It will then execute the function runningMiles and return the runningDistance value. Once the Js engine resolves the function runningMiles & returns the runningDistance value, and the local context of runningMiles gets popped off the call stack. It will then continue where it left off. It will finally resolve the value of output by storing the returned value in it.


Did I miss anything? Please let me know what you think. Feedbacks & questions are all welcome. I would love to hear your thoughts, discuss & exchange ideas. If you would love more writing like this please follow my blog or me on twitter @wolde_ai .✌🏾😊