JavaScript Working | Execution Context of JavaScript
#1 Javascript Series Started
Execution context
“Everything in Javascript happens inside an execution context”
It can be thought of as an environment where the Javascript code is evaluated and executed.
Two components of JavaScript:
Variable Environment (Memory)
Thread of Execution (Code)
Types of Execution Context:
- Global Execution Context (GEC):
The first environment that is created on the first execution of JS code. In the browser, the entire web page is a global context.
var a=2;
console.log(a);
- Function Execution content (FEC):
Every time a function is called, a new execution context is created for that function.
This context includes the function’s Parameters, local variables, and a reference to the outer execution context, which forms a chain called “scope chain” and is pushed onto “call Stack. Once the function execution is completed then that function context is popped off.
2-Phase Code Execution
Take the below code as an example to understand
let a=5;
function sum(a,b){
return a+b;
}
console.log(sum(a,4));
Phase-1: Creation Phase (Memory-Code)
In this phase-1 javascript allocates variables with undefined and functions with the entire code. In the call stack, GEC is pushed.
Phase-2: Code Execution Phase
Now, thread execution happens and all the variables get their actual values which were assigned to them. As a function is invoked, a brand new execution context for that function is created in the code part and this cycle repeats until the call stack is empty.
At last, the console will print 9. The GEC will also be popped off from the stack.