JavaScript Execution Context Cycle
Introduction
The JavaScript execution context is a critical concept to understand how JavaScript code is parsed and executed. It is the environment where JavaScript code is evaluated and executed. Understanding the execution context helps in comprehending the scope, hoisting, closures, and execution order in JavaScript.
Types of Execution Contexts
Global Execution Context (GEC)
The Global Execution Context is the default context where code that is not inside any function is executed. When a JavaScript file is loaded into a browser, the JavaScript engine creates a global execution context.
Function Execution Context (FEC)
A new Function Execution Context is created each time a function is called. Each function has its own context, which is created and destroyed dynamically as the function is invoked and returns:
Eval Execution
Context An Eval Execution Context is created when the eval() function is executed:
Phases of Execution Context
The creation of an Execution Context (GEC or FEC) happens in two phases:
Creation Phase
During the creation phase, several important tasks are performed before the code execution begins:
1. console.log(foo); // undefined
2. var foo = "Hello";
3.
4. bar(); // "Hello"
5. function bar() {
6. console.log("Hello");
7. }
Execution Phase
In the execution phase, the code within the execution context is executed line by line:
Execution Stack (Call Stack)
The Execution Stack, also known as the Call Stack, keeps track of all the Execution Contexts created during the life cycle of a script.
JavaScript is a single-threaded language, which means that it is capable of only executing a single task at a time. Thus, when other actions, functions, and events occur, an Execution Context is created for each of these events. Due to the single-threaded nature of JavaScript, a stack of piled-up execution contexts to be executed is created, known as the Execution Stack.
When scripts load in the browser, the Global context is created as the default context where the JS engine starts executing code and is placed at the bottom of the execution stack.
The JS engine then searches for function calls in the code. For each function call, a new FEC is created for that function and is placed on top of the currently executing Execution Context.
The Execution Context at the top of the Execution stack becomes the active Execution Context, and will always get executed first by the JS engine.
As soon as the execution of all the code within the active Execution Context is done, the JS engine pops out that particular function's Execution Context of the execution stack, moves towards the next below it, and so on. The approach is also known as LIFO(Last in first out).
Example:
1. var a = 10;
2.
3. function foo() {
4. var b = 20;
5. function bar() {
6. var c = 30;
7. console.log(a, b, c);
8. }
9. bar();
10. }
11.
12. foo();
Execution Cycle Breakdown: