I will discussing one of the core concept in Js i.e Execution Context. So, what really is execution context in Js. Bear with me and enjoy this fun ride.
In Js every things happens in an execution context. It basically holds the information of environment within which current code is being executed.
Js engine carries out these operation in two phases.
- Memory allocation Phase: In this phase, all the variable and function are allocated memory. Js Engine simply skims through the code for variable and function declaration and puts them in memory. Suppose we have variable declared with var a =10, It picks the “a” and puts it in memory and initialises with “undefined”.
- Code execution Phase: In this phase, the actual execution of code places i.e the Js Engine once skim through the code and execute the code it finds like variable value assignment and function call/Invocation.
Now lets see how it exactly works behind the scene
As shown in above screenshot, as soon as the code execution begins, we already have “a” in memory and its initialised to undefined. Similarly the function test() declaration is also pushed in memory at time of memory allocation phase. Now in code execution phase, a global execution context(GEC) is created and pushed in call stack, As Js engine skims through the code its pick the value of “a” and replace undefined with it. Now as it moves to function call, the GEC is paused and new execution context is created and pushed in stack. This execution context again have the same two phases. Once the execution finishes the execution context popes out of call stack and GEC resumes its execution. This process is repeated each time Js engine encounters an function invocation
*Points to remember
- The very concept of Hoisting in js related to Execution context.
- JavaScript engine creates the global execution context before it starts to execute any code.
- A new execution context gets created every time a function is executed, as the engine skims through your code.
- this refers to leading parent object in current execution context and if there is no leading parent object, then it refers to global object(window).
- In global execution context, this refers to window object i.e this === window returns true.
- Arrow function doesn’t creates an execution context that why its doesn’t have its own this.
- Let, var and const behaves differently in terms of execution context(Another big topic).
That’s all, I hope you have enjoyed this and get to know what exactly is execution context, when and how it is created.
Thanks !!