Curriculum
Module 15 // Core JavaScript
Execution Context & Call Stack
Module Objective
Global vs function execution context, creation vs execution phase, call stack behavior
Mental Model Realtime Simulation
INTERACTIVE_CANVASEditor_Pane
Loading...
Console_Output
Waiting for output...
Practical Code Examples
// Example 1
// 1. The Call Stack
function step1() {
console.log("In step 1");
step2();
console.log("Leaving step 1");
}
function step2() {
console.log("In step 2");
}
step1();💡 Stack trace: 1) Global Context pushed. 2) `step1` pushed. 3) `step2` pushed. 4) `step2` popped. 5) `step1` popped. 6) Global remains.
// Example 2
// 2. Creation vs Execution Phases
console.log(name); // undefined (Hoisted)
// console.log(age); // ReferenceError (TDZ)
var name = "Alex";
let age = 25;💡 During the **Creation Phase**, the engine allocates memory. `var` is set to `undefined`, while `let` is kept uninitialized.
// Example 3
// 3. The "this" keyword
console.log(this); // window (Global context)
const user = {
name: "Subhajit",
sayHi() {
console.log(this.name); // Subhajit (Object context)
}
};
user.sayHi();💡 The value of `this` depends on which execution context is currently active. Inside `sayHi`, the context is the `user` object.
Engine & Memory Architecture
The Engine's Workflow
1. Creation Phase (Memory Allocation):
- Variable Environment: Memory is allocated for variables and functions.
- Outer Reference: The link to the Scope Chain is built.
- 'this' Binding: The value of the
thiskeyword is determined.
2. Execution Phase (Line-by-line):
- The CPU executes the instructions.
- Values are assigned to variables.
- Function calls trigger new contexts on the Stack.
3. Hardware Context:
- The Call Stack: Lives in high-speed memory area of the RAM.
- Context Size: Each context takes a small bit of memory. Browsers limit the stack depth (usually ~10,000 calls) to protect the CPU and system stability.