DEV Community

Cover image for Stack vs Heap in JavaScript: A Practical Guide
Suvankarr Dash
Suvankarr Dash

Posted on

Stack vs Heap in JavaScript: A Practical Guide

JavaScript automatically manages memory, but understanding how the stack and heap work can help developers avoid bugs, improve performance, and prevent memory leaks.

Short Answer
Primitives and function call frames are handled on the call stack.
Objects and arrays live on the heap, with references stored on the stack.
Memory allocation and cleanup are handled by garbage collection.
This behavior is the same in browsers and Node.js.

Stack vs Heap Comparison

Aspect: -
Stores

Access speed
Lifetime
Allocation

Stack: -
Call frames, primitives, references
Fast
Short (function execution)
Automatic (LIFO)

Heap: -
Objects, arrays, functions
Slower
Long (until GC)
Dynamic

Understanding the Stack (Call Stack)
The call stack stores:
Function execution frames.
Primitive values such as numbers, booleans, null, undefined, and symbols.
When a function is called, a frame is pushed onto the stack. When it returns, the frame is popped.

Understanding the Heap
The heap stores:
Objects
Arrays
Function objects
When you create {} or [], JavaScript allocates memory on the heap and stores a reference to that object on the stack (or inside another object). The garbage collector frees heap memory when objects are no longer reachable.

Reference vs Value Example
// primitives copied by value
let a = 10;
let b = a;

// objects copied by reference
let obj1 = { x: 1 };
let obj2 = obj1;
obj2.x = 2;

console.log(obj1.x); // 2

Memory Management & Garbage Collection
You cannot manually free memory in JavaScript. Modern engines automatically reclaim heap memory when objects become unreachable.

🚨 Common risk: memory leaks caused by lingering references
βœ… Best practice: remove references to large objects when no longer needed

File Access in JavaScript
Browser
No direct file-system access
Uses File API or File System Access API
Always user-mediated and asynchronous

Ex: -

document.querySelector('input').addEventListener('change', e => {
const file = e.target.files[0];
file.text().then(console.log);
});

Node.js
Full file-system access via fs
Same V8 engine with stack/heap semantics

Ex: -
const fs = require('fs');

fs.readFile('./data.txt', 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});

Practical Tips
Avoid large global variables
Use streams for large files in Node.js
Profile memory using Chrome DevTools or Node Inspector

Top comments (0)