Understanding JavaScript Execution Context and Call Stack
A comprehensive guide to understanding how JavaScript executes code.
1. What is Execution Context?
The execution context is the environment in which JavaScript code is evaluated and executed. It contains information about the variables, functions, and the value of this
at any given point in time.
There are two main types of execution contexts:
- Global Execution Context (GEC): This is the default context where all JavaScript code runs initially.
- Function Execution Context (FEC): Created whenever a function is invoked, it contains information specific to that function.
When a script runs, the JavaScript engine creates a global execution context and pushes it onto the call stack.
2. What is Call Stack?
The call stack is a data structure that keeps track of the execution contexts created during the execution of a script. It follows the Last In First Out (LIFO) principle, meaning the last function called is the first to be executed.
When a function is called, a new execution context is created and pushed onto the stack. When the function completes, its context is popped off the stack.
Hereโs a simple example:
function first() {
second();
console.log("First function");
}
function second() {
console.log("Second function");
}
first(); // Output: Second function, First function
In this example, when first()
is called, it pushes its execution context onto the stack. Then, when second()
is called, its context is pushed on top. After second()
completes, it is popped off, and control returns to first()
.
3. How Execution Context Works
When a function is invoked, the following steps occur:
- The JavaScript engine creates a new execution context for the function.
- The function's variables and parameters are stored in the Variable Object (VO).
- The scope chain is established, allowing access to variables from outer contexts.
- The
this
value is determined based on how the function was called. - The function code is executed line by line.
Once the function completes, its execution context is removed from the call stack.