Execution Context
Execution context is an environment in which JS code is evaluated and executed. Each piece of code runs inside the execution context.
It has Three Types
- Global Execution Context
- Functional Execution Context
- Eval Execution Context: For eval() functions
Each Execution context has Two Phases
- Creation Phase
- Execution Phase
Global Execution Context
As soon as a JS file is run a Global Execution context is created. If it runs on the Browser its Window and in NodeJs its Global.
Creation Phase: JS goes through all the code and it allocates memory to all variables and functions. For variables their value is set as undefined. For functions declared with function keyword, its value is the function definition. Here value of this keyword is also set as Windows or Global object in case of Browser or NodeJs.
Execution Phase: JS goes through all the code line by line and executes it. Here the value is assigned to the variables where they are declared. functions are called where they are called. For each function execution, it creates a new smaller execution context called Functional Execution context.
Important: Global Execution Context is created only once. It is the first execution context pushed in the call stack thus it is the one which is removed at last.
Functional Execution Context
It works same as Global Execution Context but it's inside the Global execution context and it's limited to scope of the function
Creation Phase: Parameters are initialized. Variables and functions are initialized same as GEC. Value of This depends on where the function is being executed.
Execution Phase: Code is executed line by line, variables are assigned values where they are declared.
Let's understand with some code
1. Variable declarations
If you execute above code
Creation Phase | Execution Phase |
x = undefined x is initialzed with value undefined | Line 1: x is undefined Line 2: x = 20 Line 3: It will log value of x as 20 |
2. Variable declarations with let
If you execute above code
Creation Phase | Execution Phase |
x = undefined | Line 1: Cannot access 'x' before initialization Error since the variables declared with let and const are in temperal dead zone. So you cannot access them before they are declared. |
3. For functions declared with function keywords
If you execute above code
Creation Phase | Execution Phase |
x = undefined foo = function foo() { ... } | Line 1: x = 20 Line 2: It will invoke the function and log x as 20 Unlike variables function can be invoked before declaration because function are not undefined and has their definitions in creation phase. Line 3-5: Nothing happening Line 6: x = 20 |
4. For functions declared with function keywords with functional scope execution
If you execute above code
Creation Phase | Execution Phase | ||||
x = undefined foo = function foo() { ... } | Line 1: x = 20 Line 2-4: Nothing happening Line 5: Logs x as 20 Line 6: Invokes the function and creates a functinol execution context
|