In JavaScript, the Execution Context (EC) is an environment where JavaScript code is executed. It determines the scope, available variables, functions, and the value of this
.
Types of Execution Contexts
JavaScript has three types of execution contexts:
- Global Execution Context (GEC)
- Created when the JavaScript file starts executing.
- Contains the global object (
window
in browsers,global
in Node.js). this
refers to the global object.
- Function Execution Context (FEC)
- Created whenever a function is invoked.
- Has its own variables, function definitions, and
this
binding. - Each function call gets its own execution context.
- Eval Execution Context
- Created when
eval()
is used. - Executes JavaScript code inside a string (not recommended for security reasons).
- Created when
Execution Context Lifecycle
Each execution context goes through three phases:
- Creation Phase (Memory Allocation)
- Creates the Global Object (e.g.,
window
in browsers). - Sets up the “this” binding.
- Stores function declarations in memory.
- Allocates memory for variables (
var
is hoisted withundefined
,let
&const
are in TDZ).
- Creates the Global Object (e.g.,
- Execution Phase
- Executes the code line by line.
- Assigns values to variables.
- Executes function calls.
- Destruction Phase
- The execution context is removed from the call stack once execution is complete.