Skip to main content

Command Palette

Search for a command to run...

Execution Context in JavaScript

Updated
2 min readView as Markdown
Execution Context in JavaScript
A

Hi, My name is Ankush Sharma. I started my web development journey in December 2020. Till now I've built 5 full-stack projects in the MERN stack.

What is execution context?

Execution Context is like a box or container in which javascript code gets executed. Execution Context consists of two components that are memory component and the code component. In the memory component, memory is allocated to all variables and functions along with the code and they are stored as key-value pairs in the memory. The memory component is also called variable environment. In the code component, the code gets executed one line at a time. It is also called the thread of execution. Once the code of a function gets executed, the execution context of that function (which was invoked) is popped or removed from the call stack. We may have multiple functions, so there will be multiple execution contexts so to keep the track of the order of execution contexts, a call stack is used. When a javascript program is executed, then a global execution context is created. At the bottom of the call stack, a global execution context gets popped or removed from the call stack after the whole javascript code has been executed.

Blank Diagram.jpeg

Let's consider an example:

let num = 5
function example (a){
    let ans = a + a;
    return ans;
};

let sum = example(num);

The first thing the JS engine does is that it goes through the whole program and creates a variable environment(or memory component) and stores the variable at the first line of the code and allocates memory space for variable 'num'. Then it goes to the next line and allocates memory space to the function "example". And similarly, it allocates memory space for the variable "sum".

When allocating memory, for variable 'num' and 'sum' it stores undefined in its memory space and for function "example" it stores the body of the function in its memory space as a key-value pair.

image.png

When a function is invoked an execution context of the function is created in which there are memory and code component.

image.png

So, the function example execution context is created and the memory is allocated to all the variables and arguments of the function as shown above. Now, as soon as the value is returned from the function, the control of execution goes back to where the function was invoked i.e. line number 7, and the execution context of the function example is popped or removed from the call stack as shown below.

image.png

And the sum is initialized with the returned value. After the execution of the code is done the global execution context(or anonymous) is also removed from the call stack.