What is Execution Context in JavaScript?
Hello Everyoneđź‘‹, In this article, we will take a look into how the JavaScript codes run in the background.
Introduction
Whenever we execute a JS code. The JavaScript engine first creates a Global Execution Context. Global Execution Context has two phases:
- Creation phase
- Execution phase
Creation phase
On first time code run, the Global Execution Context goes in the Creation phase where the following things happen:
- Creation of global object
window
in the web browser andglobal
in Node.js - Creation of global variable
this
- Allocates memory for storing variable and functions references.
In this phase, the engine goes through all the global variables and functions. The variables are initialized with primitive data type undefined
and the functions get placed directly into memory. After all this, the global execution context moves to the execution phase.
Let's look into one example,
let a=4;
let b=3;
function add(num1,num2){
console.log(num1+num2);
}
add(a,b);
Explanation:
This code will first go through a creation phase where memory allocation will be done for variables and functions. Here, a and b will be allocated memory with an undefined
value. The whole add function will be allocated a memory.
Execution phase
In this phase, the engine executes the code line by line. It assigns the values to the global variables. For every function call, the engine creates a Function Execution Context inside Global Execution Context and every Function Execution context has the same phases as that of the global execution context. If there is another function inside a function then a separate function execution context is created on top of context. Let's see the above example's execution phase,
Explanation:
In this phase, variable a and b will be assigned with 4 and 3 value. On line 6, a function is invoked. As mentioned before, for every function call, a function execution context is created and it gets stacked on the global execution context. Here, after the creation of function execution context. The code inside of the add()
function enters the creation phase first. After initializing all the variables with undefined
it will enter the execution phase. In the execution phase after executing the code inside the function. The engine will return to the global execution context.
Conclusion
JavaScript is a single-threaded language that's why it can process one thing at a time. More than one event is processed one after another in JavaScript.
I hope you enjoyed this article and got a glimpse about Execution context. Feel free to connect me on Twitter