⭐ 1️⃣5️⃣ What Is an Execution Context?
When JavaScript runs code, it creates an execution context.
An execution context is the environment in which JavaScript evaluates and executes code.
At a high level, there are different kinds of execution contexts.
The most important ones initially are:
• Global Execution Context: Created when your JavaScript program begins executing.
• Function Execution Context: Created whenever a function is called.
For example:
const name = "Rahul";
function greet() {
const message = "Hello";
console.log(message);
}
greet();
Conceptually:
Global Execution Context
↓
greet() called
↓
Function Execution Context
1️⃣6️⃣ Creation Phase and Execution Phase
A simplified mental model is that JavaScript prepares an execution context before executing its statements.
During setup, JavaScript determines things such as:
• Variable bindings
• Function declarations
• Lexical environments
Then JavaScript executes the code.
For example:
var age = 25;
function greet() {
console.log("Hello");
}
During the setup process, JavaScript prepares the relevant bindings.
Then execution proceeds through the statements.
This helps explain why function declarations and "var" behave differently from "let" and "const".
1️⃣7️⃣ Execution Context Stack
JavaScript uses a call stack to keep track of active function execution.
Example:
function first() {
second();
}
function second() {
third();
}
function third() {
console.log("Hello");
}
first();The execution roughly looks like:
third()
↑
second()
↑
first()
↑
Global
When "third()" finishes:
third() removedThen:
second() finishesThen:
first() finishesEventually the stack becomes empty.
⭐ 1️⃣8️⃣ Call Stack
The call stack follows:
LIFO (Last In, First Out)
For:
function first() {
second();
}
function second() {
console.log("Hello");
}
first();The stack conceptually becomes:
1. Global
2. first()
3. second()
Then:
second() removedfirst() removedGlobal continues
Understanding the call stack becomes very important when we later study:
• Callbacks
• Asynchronous JavaScript
• Promises
• Event loop
• Stack overflow
⭐ 1️⃣9️⃣ Scope vs Execution Context
These concepts are related but not identical.
• Scope answers: "Where can this variable be accessed?"
• Execution context answers more broadly: "What environment is JavaScript using while executing this code?"
For example:
const name = "Rahul";
function greet() {
const message = "Hello";
console.log(name);
console.log(message);
}
Scope determines which variables are accessible.
Execution context represents the environment created when "greet()" is actually executed.
⭐ 2️⃣0️⃣ Closures Preview
Closures are built on lexical scope.
Consider:
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());Output:
1
2
3
The returned function continues to access "count" even after "createCounter()" has finished executing.
🚀 Double Tap ❤️ For More