Call Stack + Heap + Memory: How JavaScript Stores and Runs Your Code
Call Stack + Heap + Memory: How JavaScript Stores and Runs Your Code
Every JavaScript program you write — from a small button handler to a full e-commerce platform — runs on two pieces of memory working together: the call stack and the heap. If you understand how they work, you will understand why recursion can crash a page, why objects behave differently from numbers, and where memory leaks actually come from.
At Ovlyc, this mental model is one of the first things we teach developers joining a project, because it explains so many real-world bugs that look mysterious until you see what is happening in memory.
The Two Regions of JavaScript Memory
When the JavaScript engine (V8 in Chrome and Node.js) starts your program, it reserves memory in two main regions:
- The call stack — a small, fast, strictly ordered region that tracks what is currently running.
- The heap — a large, unstructured region that stores the data your program creates: objects, arrays, functions, and closures.
They have opposite jobs. The stack is about execution order. The heap is about storage. Your code touches both constantly, often without you noticing.
The Call Stack: One Function at a Time
The call stack is a last-in, first-out (LIFO) structure. Think of it as a stack of plates: you can only add to the top and remove from the top.
Every time a function is called, the engine pushes a new stack frame onto the stack. That frame holds the function's local variables and a return address — where to go back to when the function finishes. When the function returns, its frame is popped off.
function multiply(a, b) {
return a * b;
}
function square(n) {
return multiply(n, n);
}
function printSquare(n) {
const result = square(n);
console.log(result);
}
printSquare(5);
As this runs, the stack grows and shrinks:
1. printSquare(5) is pushed.
2. It calls square(5), which is pushed on top.
3. square calls multiply(5, 5), pushed on top.
4. multiply returns 25 and is popped.
5. square returns 25 and is popped.
6. printSquare logs the result and is popped. The stack is empty again.
This is why JavaScript is called single-threaded: there is exactly one call stack, so only one function executes at a time.
Stack Overflow: When the Stack Runs Out
The stack is small — typically a few megabytes, enough for roughly ten thousand nested calls. If a function keeps calling itself without ever returning, the stack fills up and the engine throws an error:
function countDown(n) {
return countDown(n - 1); // never stops, never returns
}
countDown(10); // RangeError: Maximum call stack size exceeded
Every call adds a frame and nothing is ever popped. This "Maximum call stack size exceeded" error is the stack telling you it has no room left. In practice, you will hit it with runaway recursion — a function that calls itself without a correct base case — or with deeply nested data structures processed recursively. The fix is usually a proper base case, or rewriting the recursion as a loop for very deep data.
The Heap: Where Objects Live
While the stack is ordered and small, the heap is a large pool of unordered memory. When you create an object, an array, or a function, JavaScript allocates space for it in the heap. The heap does not care about order or nesting — it just hands out memory and keeps track of what is still in use.
const user = { name: "Ayesha", role: "admin" };
const scores = [92, 88, 95];
Here, user and scores are not the objects themselves. They are references — small pointers stored on the stack that point to the real data in the heap. This distinction is the key to understanding how JavaScript handles values.
Primitives vs. References: The Rule That Explains Most Surprises
JavaScript has two kinds of values, and they live in different places:
Primitives — numbers, strings, booleans, null, undefined, symbols, and bigints — are stored directly on the stack. Copying a primitive copies the value itself:
let a = 10;
let b = a;
b = 20;
console.log(a); // 10 — a is untouched
Objects — including arrays and functions — are stored in the heap, and variables hold only a reference to them. Copying an object variable copies the reference, not the object:
const user1 = { name: "Ayesha" };
const user2 = user1;
user2.name = "Rahim";
console.log(user1.name); // "Rahim" — both point to the same object
This is why passing an object into a function can change the original, while passing a number cannot. It is also why comparing two objects with === checks whether they are the same object in the heap, not whether they have equal contents:
console.log({ a: 1 } === { a: 1 }); // false — two different objects
If you need a genuinely independent copy of an object, you must clone it — with structuredClone(), the spread operator for shallow copies, or a dedicated deep-clone utility.
Memory Management: The Garbage Collector
You never allocate or free memory manually in JavaScript. The engine's garbage collector does it for you, using a simple rule: if an object can still be reached from your code — through a variable, a closure, or another live object — it stays. Once nothing references it anymore, it is eligible for collection.
function createReport() {
const report = { rows: new Array(10000).fill("data") };
return report.summary;
}
createReport();
// The big report object has no references left — the garbage collector frees it.
Modern engines use a mark-and-sweep algorithm: they start from the "roots" (global variables and the current stack), mark everything reachable, and sweep away everything unmarked. V8 also uses a generational design — new objects go into a "young generation" that is cleaned frequently, while objects that survive several cleanups are promoted to an "old generation" cleaned less often. Most objects die young, so this design keeps collection cheap.
You do not need to manage this yourself, but you do need to avoid holding references you no longer need. That is exactly what a memory leak is in JavaScript.
Memory Leaks: References You Forgot to Release
A memory leak happens when the heap keeps growing because objects that should be dead are still reachable. The most common causes in real applications are:
1. Forgotten timers and intervals — a setInterval that keeps running after its component is removed keeps everything it references in the heap forever. Always clearInterval on cleanup.
2. Event listeners that are never removed — an unremoved listener keeps both the handler and everything it closes over alive, even after the element itself is gone.
3. Accidental global variables — assigning without const/let puts the variable on the global object, which is a garbage-collection root, so it is never collected.
4. Closures holding large data — a returned function that closes over a huge dataset keeps that whole dataset alive for as long as the function itself lives.
In production, you can spot these problems with the browser's DevTools Memory tab or Node.js heap snapshots — tools we will cover later in this series when we look at profiling and heap snapshots in depth.
Stack, Heap, and the Event Loop Working Together
The stack and heap do not work alone. When your code calls setTimeout or fetches data, the engine hands that work to browser or Node.js APIs outside the stack. The callback that comes back waits in a queue, and the event loop pushes it onto the stack only when the stack is empty. The data that callback needs — your response object, your variables — lives in the heap in the meantime, kept alive by the closure that references it.
That is the full picture in one sentence: the stack decides what runs now, the heap holds what your code needs, and the event loop brings delayed work back to the stack when it is ready.
Why This Matters When You Build Products
Understanding the call stack and the heap changes practical decisions:
- Keep functions short and returning. Deep call chains and unbounded recursion are the fastest way to a stack overflow.
- Treat objects as shared, not copied. Before mutating an object passed into a function, ask whether the caller expects the original to change.
- Clean up what you create. Every setInterval, event listener, and subscription needs a matching teardown, or the heap will hold it forever.
- Watch what closures capture. A tiny handler that closes over a large object keeps that whole object in memory.
- Do not fear the garbage collector — respect it. It frees memory you stop referencing. Your job is to stop referencing things on time.
At Ovlyc, these rules show up in every code review. A dashboard that slowly gets heavier over a workday is almost always a listener or interval that was never cleaned up. A form that corrupts data on save is almost always a shared object reference mutated in two places. Once you can picture the stack and the heap, both bugs become easy to see before they ship.
The Big Picture
JavaScript memory is two simple ideas working together. The call stack is a strict, ordered record of the functions currently running — push on call, pop on return, overflow if you never return. The heap is a large, flexible store for the objects and data those functions work with, managed automatically by the garbage collector and kept alive only as long as something still references them.
Primitives live by value on the stack. Objects live by reference in the heap. Everything else — closures, the event loop, memory leaks, performance — follows from that one distinction.
In the next article, we will build on this foundation with the JavaScript event loop itself: how one thread juggles timers, promises, and network requests without ever blocking.
Related Articles
What Is Node.js? JavaScript Beyond the Browser
Learn what Node.js is, how its V8 engine, libuv, and event loop work, and when to use it for APIs, real-time apps, and full-stack JavaScript.
Execution Context: Where JavaScript Variables Actually Live
Learn how JavaScript execution contexts work — the creation and execution phases, hoisting, the scope chain, closures, and how this is decided.
Microtask vs Macrotask: Why Promises Jump the Queue in JavaScript
Why a zero-delay timer loses to a promise: JavaScript's microtask and macrotask queues explained, with examples of promises, timers, and event-loop starvation.
Explain the JavaScript Event Loop: How One Thread Handles Everything
How JavaScript's single thread stays responsive: the call stack, callback and microtask queues, timers, and why blocking the loop freezes everything.