Execution Context Explained
What is Execution Context?
Execution Context is the environment in which JavaScript code is executed.
In simple terms:
It is the place where your code runs and decides how variables and functions behave.
Why Execution Context is Important
Execution context controls:
- Which variables are accessible (scope)
- When functions are executed
- Order of execution
- How hoisting works internally
Types of Execution Context
There are two main types:
1. Global Execution Context (GEC)
- Created when the JavaScript program starts
- Only one global execution context exists
- All global variables and functions are stored here
Example:
let a = 10;
function test() {
console.log("Hello");
}
test();
Here:
a→ stored in global memorytest()→ stored in global memory
2. Function Execution Context (FEC)
- Created every time a function is called
- Each function call creates a new execution context
- Destroyed after function execution completes
Key Point:
Multiple function execution contexts can exist, but only one global execution context exists.
Phases of Execution Context
Each execution context has two phases:
Memory Creation Phase
Also called Creation Phase
In this phase:
- Memory is allocated for variables
- Variables are initialized with
undefined - Functions are stored entirely in memory
Example:
var a = 10;
function greet() {
console.log("Hi");
}
During memory phase:
a = undefined
greet = function() {...}
2. Code Execution Phase
In this phase:
- Code runs line by line
- Variables get actual values
- Functions are executed when called
After execution:
a = 10
Execution Flow (Step-by-Step)
- Global Execution Context is created
- Memory Creation Phase runs
- Code Execution Phase runs
- When a function is called:
- New Function Execution Context is created
- Function executes
- Function Execution Context is destroyed
- Control returns to Global Execution Context
Relationship Between Hoisting and Execution Context
Hoisting happens because of the Memory Creation Phase.
- Variables are stored with
undefined - Functions are stored completely
- That’s why you can use them before declaration
Example:
console.log(a); // undefined
var a = 10;
This works because:
ais already created in memory before execution