Topic 4 of 37
Memory Heap vs. Call Stack
Overview
The JS engine uses two main areas: The Memory Heap (where objects and large data structures are stored randomly) and the Call Stack (which tracks where we are in the code and executes functions). Knowing these helps you understand stack overflows and memory leaks.
Syntax
first() is pushed to the stack. Inside first(), second() is pushed. second() finishes and pops off, then first() finishes and pops off.
Call Stack Execution
javascript
function first() {
console.log("First");
second();
}
function second() {
console.log("Second");
}
first();Common Pitfalls
- Creating infinite recursive loops that blow up the Call Stack.
- Keeping references to unused objects, which fills up the Memory Heap (Memory Leak).
Interview Tips
- Mention that primitives go on the Call Stack, while objects go on the Memory Heap with a reference kept on the Stack.
Real-World Example
A Stack Overflow error occurs when the Call Stack size is exceeded.
example
javascript
// Infinite recursion causing Maximum call stack size exceeded
function inception() {
inception();
}
// inception(); // UNCOMMENT TO CRASH THE STACK