JavaScript Execution Context

JavaScript Execution Context

·

2 min read

When the JavaScript code started to run then the Global Execution Context is created.

Types of Phases in Execution Context

The Execution context is created in two phases:

  1. Memory allocation Phase

  2. Code Execution phase

Let's start with the following example:

1  let index = 55
2
3  function multi (number){
4    return  number + number;
5  }
6
7  let answer = multi(index)
8  console.log(answer);

1. Memory allocation Phase

JS will allocate memory to all the variables and functions.

Let's see how this function works inside the GEC

So in the first phase, js runs through the whole program line by line & it allocates memory to all the variables and functions as soon as it encounters 'n', it reserves memory for it & allocates a special value 'Undefined'.

This whole function code is literally copied over here in the memory space.

And for the remaining variables again allocates and stores this special keyword 'Undefined'.

The second phase is the code execution phase. It is the code execution phase after the memory allocation. So, JS once again runs through this whole JS program line by line & it executes the code now. So As soon as it encounters this first line, index=55.

After finishing line one, it goes to line two and sees that we have nothing to do here so from line number three to five, there is nothing to execute literally.

This return keyword state now return the control of the program, to the place where this function was run.

And the code will then move to line number 3 it will do calculations & put the value of number+number inside the answer.

After all the function code is executed, then that function execution context removed

Call Stack

Let's start with the following example:

1  let index = 55
2
3  function multi (number){
4    return  number + number;
5  }
6
7  let answer = multi(index)
8  console.log(answer);

The call stack is like a stack every time at the bottom of the stack we have the Global execution context.

Whenever a function is run or a new execution context is created, So this execution context is put inside the stack once done with executing function, it returns the answer.

The multi() moved out of the stack, and all control goes back to the Global Execution Context (GEC). If again added new execution the code will run like a loop.