Execution Context in JavaScript
🔍 What is an Execution Context?
In JavaScript, the Execution Context is the environment in which code is evaluated and executed. It's like a wrapper that helps the JavaScript engine keep track of what code is currently running, what variables are available, and how the scope chain is constructed.
🧱 Types of Execution Contexts
- Global Execution Context (GEC) – Created when the script first runs.
- Function Execution Context (FEC) – Created every time a function is invoked.
- Eval Execution Context – Created by code inside eval() (rarely used).
Note
JavaScript is single-threaded and executes code one context at a time using a Call Stack.
🚦 How Execution Context Works
Every execution context goes through two phases:
- Creation Phase – Variables, functions, and the scope chain are set up.
- Execution Phase – Code is executed line by line.
📌 Example
Execution Context Flow
var name = "JavaScript";
function greet() {
var greeting = "Hello";
console.log(greeting + " " + name);
}
greet();Here's what happens step-by-step:
- 🔹 GEC is created → name is defined.
- 🔹 greet() is called → FEC is created.
- 🔹 Inside FEC, greeting is defined and logged.
- 🔹 FEC is destroyed after completion.
⚙️ Execution Stack (Call Stack)
JavaScript uses a Call Stack to manage execution contexts. The GEC is always at the bottom. Every time a function is called, a new FEC is pushed to the stack.

Note
When a function finishes execution, its context is popped off the stack.
🔍 Visualizing the Context
| Context | Phase | Details |
|---|---|---|
| Global | Creation | Creates global variables and functions |
| Global | Execution | Executes code line-by-line |
| Function | Creation | Sets up local variables and scope |
| Function | Execution | Runs the function’s code |
📚 Summary
- Each execution context manages variable scope and execution flow.
- JavaScript creates a stack of contexts as code runs.
- Understanding contexts is crucial for mastering this, closures, and hoisting.
>>“To master JavaScript, you must first understand how it thinks.”