Stack & Heap
Overview
The Stack and the Heap are two distinct areas of memory that the JavaScript engine uses while your code runs.
Understanding how they work is the key to understanding why Primitives and Reference Types behave so differently.
Syntax
The Call Stack is highly organized, fast, and strict. It stores Primitive types directly because their sizes are fixed and small.
let name = "Kartik";
let age = 22;The Memory Heap is an unorganized, large space for dynamic data. When you create an object, the massive object data goes into the Heap, and a tiny pointer to that location is saved on the Stack.
let user = {
name: "Kartik",
role: "Developer"
};Common Pitfalls
- Assuming a huge array stored in a variable is kept on the stack. The variable only holds a tiny memory address. This is why passing massive objects around your app is actually very fast!
Interview Questions
The Stack requires fixed, known memory sizes at compile time (like numbers and booleans). Objects and Arrays are dynamic (they can grow and shrink), so they require the flexibility of the Heap.
Garbage collection is an automatic process. When an object in the Heap no longer has any variables pointing to it from the Stack, the JS engine deletes it to free up memory.
Real-World Example
If you build an infinite loop that keeps creating new objects without releasing them, you will fill up the Heap until the browser tab crashes (Memory Leak).
let memoryLeakArray = [];
// Never do this!
setInterval(() => {
memoryLeakArray.push({ hugeData: "..." });
}, 10);Check Your Knowledge
Test your understanding of Stack & Heap with these quick questions.