Heap and stack in Node.js
1. What a Node.js process's memory looks like
When you run a Node.js application, the system allocates it a region of memory. That memory splits into two main parts:
| Area | Purpose |
|---|---|
| Stack | Holds execution context: functions, primitive-type variables and return addresses. |
| Heap | Holds objects, arrays, functions, closures, everything created dynamically. |
Both areas are managed by the V8 engine built into Node.js.
2. The stack
The stack is an ordered LIFO (Last In, First Out) structure. It stores function call context.
Example:
function a() {
const x = 10;
b();
}
function b() {
const y = 20;
console.log(y);
}
a();What happens:
- Calling
a()creates a frame on the stack:
[ a() ]a()callsb(), so a new frame is pushed on top:
[ b() ]
[ a() ]- When
b()finishes, its frame is removed:
[ a() ]- When
a()finishes, the stack is empty.
Primitive values (number, boolean, undefined, null, symbol, bigint)
and references to objects live on the stack.
3. The heap
The heap is a dynamic memory area that holds objects, arrays, functions, closures, classes: everything with a variable size that outlives a single function call.
Example:
function createUser() {
const user = { name: 'Tim', age: 25 };
return user;
}
const u = createUser();- The stack holds a reference to
user. - The object
{ name: 'Tim', age: 25 }itself lives on the heap.
The garbage collector (GC) manages the heap: once an object has no more references, the GC frees its memory.
4. Visually:
Stack: (fast, small, LIFO)
┌──────────────────────┐
│ main() │
│ ├─ userRef → (heap) │
│ └─ total = 42 │
└──────────────────────┘
Heap: (large, dynamic)
┌────────────────────────────────────────┐
│ { name: "Tim", age: 25 } │
│ [1, 2, 3, 4, 5] │
│ function user() {...} │
└────────────────────────────────────────┘5. Stack vs heap differences
| Criterion | Stack | Heap |
|---|---|---|
| Data type | Primitives, references, call context | Objects, arrays, functions |
| Size | Small and fixed | Large and dynamic |
| Access speed | Very fast | Slower |
| Lifecycle | Freed automatically when a function returns | Managed by the garbage collector |
| Management | Sequential (LIFO) | Unordered (the GC decides what to remove) |
| Errors | Stack overflow | Memory leak |
6. Stack overflow
If recursion or function calls never end, the stack overflows:
function recurse() {
recurse();
}
recurse(); // RangeError: Maximum call stack size exceededEvery function call adds a frame to the stack, so recursion that's too deep overflows it.
7. Garbage collection and the heap
V8 automatically frees heap memory once an object becomes unreachable (has no references left):
let user = { name: 'Tim' };
user = null; // now the object is unreachable → the GC will free its memoryV8 splits the heap into two parts:
- New Space, for new objects (fast, collected often);
- Old Space, for "long-lived" objects (collected less often, but with more work).
8. Performance
- Stack operations (for example, arithmetic, function calls) are very fast.
- Heap operations are slower: memory has to be allocated, references followed, and the GC has to do work.
That's why creating fewer temporary objects and reusing data structures is a real optimization for Node.js code.
9. An example combining stack and heap
function addUser() {
const id = 1; // stack
const user = { id, name: 'Tim' }; // heap
return user;
}
const u = addUser(); // u (stack) → {id: 1, name: 'Tim'} (heap)id(a primitive) lives on the stack;- the
userobject lives on the heap; - the
uvariable on the stack holds a reference to the object on the heap.
10. Summary
| Area | Description |
|---|---|
| Stack | A fast memory area for function calls and primitives. Managed automatically. |
| Heap | A dynamic memory area for objects, arrays and functions. Managed by the garbage collector. |
| The link | The stack holds references to objects that live on the heap. |
| Errors | A stack overflow comes from deep recursion. A memory leak comes from holding unneeded references. |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.