Skip to main content

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:

AreaPurpose
StackHolds execution context: functions, primitive-type variables and return addresses.
HeapHolds 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:

javascript
function a() { const x = 10; b(); } function b() { const y = 20; console.log(y); } a();

What happens:

  1. Calling a() creates a frame on the stack:
javascript
[ a() ]
  1. a() calls b(), so a new frame is pushed on top:
javascript
[ b() ] [ a() ]
  1. When b() finishes, its frame is removed:
javascript
[ a() ]
  1. 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:

javascript
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:

javascript
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

CriterionStackHeap
Data typePrimitives, references, call contextObjects, arrays, functions
SizeSmall and fixedLarge and dynamic
Access speedVery fastSlower
LifecycleFreed automatically when a function returnsManaged by the garbage collector
ManagementSequential (LIFO)Unordered (the GC decides what to remove)
ErrorsStack overflowMemory leak

6. Stack overflow

If recursion or function calls never end, the stack overflows:

javascript
function recurse() { recurse(); } recurse(); // RangeError: Maximum call stack size exceeded

Every 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):

javascript
let user = { name: 'Tim' }; user = null; // now the object is unreachable → the GC will free its memory

V8 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

javascript
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 user object lives on the heap;
  • the u variable on the stack holds a reference to the object on the heap.

10. Summary

AreaDescription
StackA fast memory area for function calls and primitives. Managed automatically.
HeapA dynamic memory area for objects, arrays and functions. Managed by the garbage collector.
The linkThe stack holds references to objects that live on the heap.
ErrorsA stack overflow comes from deep recursion. A memory leak comes from holding unneeded references.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.