Execution Context in Javascript
anjan-dutta
Posted on July 28, 2021
The execution context in javascript is an environment. Usually when we run a function, it is executed in the execution context.
Confusing? Don’t worry, consider the below code:
var c= 5;
function random() {
return 10;
}
function multiply() {
return c * random()
}
multiply();
Take a look at the above code. When the javascript engine starts executing the above code, it creates the Call Stack in memory.
We might ask what is a call stack and how it is related to execution context in Javascript?
Think of it as a simple stack. This stack contains the function blocks one after another in a bottom up approach.
During execution, when the compiler gets any new function, it pushes the function in the call stack.
One after another, the code blocks will be pushed in the stack. These code blocks are the execution contexts.
Now, the question is, how does the engine distinguishes each block of code?
It is not actually the lines of code. When the compiler encounters a new function call or code block it creates an execution contexts in javascript.
Execution context in javascript can be any of the three types below:
Global Execution Context: This is the default execution context. It contains the global variable declarations and function calls. Global execution contexts are unique and always the starting point of execution.
Function Execution Context: The code, inside a function definition or the function body itself.
Whenever the global or functional context encounters another function, a new execution context is created in call stack.
Eval: The code, inside an eval expression.
Each execution context has 2 stages. A creation stage and an execution stage.
Creation stage in execution context:
- In creation stage, javascript scans the code and declares all variables and assigns undefined as the value of those variables.
- Creates the scope chain.
- Set value of this object.
Execution stage in execution context:
- Javascript engine scans the code and assigns value to all variable objects.
- Along with that it executes the code line by line.
Below is the order of execution context creation in call stack for above code.
Posted on July 28, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.