Tutorials JavaScript Memory Management & GC
Ch 64 / 78
Chapter 64 Advanced 8 min read JavaScript

Memory Management & Garbage Collection

JavaScript handles memory automatically — but "automatic" doesn't mean "magic". Understanding how the engine allocates memory, how the Garbage Collector reclaims it, and what patterns cause memory leaks will make you a far more effective developer — especially on long-running SPAs and Node.js servers.

What you'll learn
The three-phase memory lifecycle: allocate → use → release
Difference between the Stack (primitives) and Heap (objects)
How the Mark-and-Sweep GC algorithm works
The four most common memory leak patterns
How WeakMap & WeakRef enable GC-friendly data structures
Profiling memory in Chrome DevTools

The Memory Lifecycle

Every piece of data your program touches goes through the same three-phase lifecycle, regardless of the language. JavaScript automates phases 1 and 3 — but you need to understand all three to avoid problems.

1
Allocate
Engine reserves memory when you declare variables, create objects, or call functions.
2
Use
Your code reads from and writes to the allocated memory during execution.
3
Release
When memory is no longer needed, the GC identifies and frees it for reuse.

In low-level languages like C, you manually call malloc() and free(). In JavaScript, the engine handles this — but the GC can only free memory it can prove is unreachable. If you accidentally keep a reference alive, memory is never freed.

Stack Memory vs Heap Memory

JavaScript stores data in two regions. Understanding which goes where explains why primitives behave differently from objects:

Call Stack (Static Memory)
let age = 25 25
let flag = true true
let name = "K2" "K2"
let obj → ref 0x1a4f ↗
Heap (Dynamic Memory)
0x1a4f → { } Object
0x2b3c → [ ] Array
0x3d8e → fn Function
0x4c11 → { } Object
Stack — Primitives
number, string, boolean, null, undefined, symbol, bigint are stored directly on the stack. Fixed size, fast access, automatically freed when the function returns.
Heap — Objects / Functions
Objects, arrays, and functions live on the heap. The variable on the stack holds a reference (pointer) to the heap address. Multiple variables can point to the same object — mutating it through any reference affects all of them.
JavaScript — Value vs Reference
// ── Primitives: copied by VALUE ──────────────────────────
let a = 10;
let b = a;     // b gets its own copy of 10
b = 99;
console.log(a); // 10 — unchanged

// ── Objects: copied by REFERENCE ─────────────────────────
let obj1 = { score: 10 };
let obj2 = obj1; // both point to the SAME heap object
obj2.score = 99;
console.log(obj1.score); // 99 — obj1 also changed!

// To truly copy an object, use spread or structuredClone:
let obj3 = { ...obj1 };     // shallow copy
let obj4 = structuredClone(obj1); // deep copy (ES2022+)

Garbage Collection — Mark-and-Sweep

Modern JS engines (V8, SpiderMonkey) use a Mark-and-Sweep algorithm as the foundation of garbage collection. It works in two passes:

Phase 1 — Mark
The GC starts from a set of roots (global variables, currently executing functions, local variables on the call stack). It traverses every object reachable from a root and marks it as "alive".
Phase 2 — Sweep
Any object in the Heap that was not marked is considered unreachable — no part of your code can ever access it again. The GC frees that memory so it can be reused.

Here's a visual of which objects survive and which are collected:

Global Root
ROOT
obj A
✓ REACHABLE
obj B
✓ REACHABLE
obj C
✗ COLLECTED
obj D
✗ COLLECTED
obj E
✓ REACHABLE
JavaScript — How GC detects unreachable objects
let user = { name: "Ravi" }; // heap object, referenced by 'user'

user = null; // reference dropped — object is now unreachable
// GC will collect { name: "Ravi" } on next cycle ✅

// ── Two references to the same object ────────────────────
let admin = { name: "Admin" };
let backup = admin;   // second reference

admin = null;  // one reference dropped
// Object STILL reachable via 'backup' — NOT collected

backup = null; // now truly unreachable — GC will collect it ✅

// ── Circular references (no longer a problem in modern GC) ──
function createCycle() {
  let x = {};
  let y = {};
  x.ref = y;  // x → y
  y.ref = x;  // y → x (circular!)
  // When createCycle() returns, x and y are both unreachable
  // Mark-and-sweep correctly collects them both ✅
}
createCycle();
V8 Generational GC
V8 uses a generational garbage collector — it divides the heap into a small Young Generation (frequent minor GC, very fast) and a larger Old Generation (infrequent major GC). Most short-lived objects never leave the Young Generation, keeping GC pauses minimal.
⚡
Free Resource
Download our JavaScript Performance Cheat Sheet
Memory tips, GC triggers, profiling commands — all on one page.
Get Sheet

Common Memory Leak Patterns

A memory leak occurs when memory that is no longer needed is never released — because something still holds a reference to it. Here are the four most frequent culprits in JavaScript:

Accidental Globals
Variables declared without let/const/var silently become properties on window — they live forever until the page unloads.
Forgotten Timers
setInterval keeps its callback and everything it closes over alive indefinitely. Always call clearInterval() when done.
Detached DOM + Listeners
Removing a DOM node doesn't remove its event listeners. If JS still holds a reference to the node, the node (and the listener) can't be collected.
Closures Over Large Data
A closure captures its enclosing scope. If a long-lived closure captures a large object that's no longer needed, the object is stuck in memory.
JavaScript — Leak Pattern 1: Accidental Global
function processData() {
  cache = []; // ❌ no 'let/const' — becomes window.cache!
  for (let i = 0; i < 1_000_000; i++) cache.push(i);
}
processData(); // window.cache holds 1M numbers forever

// ✅ Fix: always declare variables explicitly
function processDataFixed() {
  const cache = []; // scoped to this function, freed on return
  for (let i = 0; i < 1_000_000; i++) cache.push(i);
}
JavaScript — Leak Pattern 2: Forgotten setInterval
let bigData = new Array(100_000).fill("data");

// ❌ interval runs forever, closure keeps bigData alive
setInterval(() => {
  console.log(bigData.length);
}, 1000);

// ✅ Fix: always store and clear the interval ID
const id = setInterval(() => {
  console.log(bigData.length);
}, 1000);

// When no longer needed:
clearInterval(id);
bigData = null; // now GC can collect the array
JavaScript — Leak Pattern 3: Detached DOM node
let detachedNode;

function create() {
  const div = document.createElement("div");
  document.body.appendChild(div);
  detachedNode = div; // ❌ JS still references the node
}

function remove() {
  document.body.removeChild(detachedNode);
  // Node removed from DOM but 'detachedNode' still holds it — LEAK

  // ✅ Fix: null out the reference after removal
  detachedNode = null; // now GC can collect it
}
JavaScript — Leak Pattern 4: Closure over large data
function makeLogger() {
  const hugeReport = new Array(500_000).fill("report line");

  // ❌ returned closure captures hugeReport — never freed
  return function log(msg) {
    console.log(msg, hugeReport.length);
  };
}

const logger = makeLogger(); // hugeReport stays in memory forever

// ✅ Fix: extract only what you need from the large data
function makeLoggerFixed() {
  const hugeReport = new Array(500_000).fill("report line");
  const count = hugeReport.length; // capture only what's needed

  // hugeReport goes out of scope — GC can collect it
  return function log(msg) {
    console.log(msg, count);
  };
}

WeakMap, WeakSet & WeakRef — GC-Friendly References

JavaScript provides weak reference types specifically for cases where you want to associate data with an object without preventing it from being garbage collected:

Type Keys / Values Prevents GC? Use Case
Map Any type
Yes — strong refs
General key-value store
WeakMap Keys must be objects
No — weak keys
Private data, DOM metadata, caches
Set Any type
Yes — strong refs
Unique value collections
WeakSet Objects only
No — weak refs
Tracking object "tags" without leaking
WeakRef Wraps one object
No — weak ref
Optional caching — object may be collected
JavaScript — WeakMap for private DOM metadata
// Using a regular Map — DOM nodes are never GC'd even when removed
const domMap = new Map();

// ✅ WeakMap — when the DOM node is removed, its entry is auto-collected
const domMeta = new WeakMap();

function attachMeta(element, data) {
  domMeta.set(element, data); // no strong reference kept
}

let btn = document.querySelector("#myBtn");
attachMeta(btn, { clicks: 0, created: Date.now() });

// When btn is removed from DOM and set to null,
// WeakMap entry is automatically garbage collected ✅
btn.remove();
btn = null;
JavaScript — WeakRef for optional caching
let cache = null;

function getExpensiveData() {
  // Check if cached value still exists in memory
  if (cache) {
    const data = cache.deref(); // deref() returns the object or undefined
    if (data) {
      console.log("✅ Cache hit");
      return data;
    }
  }

  // Cache miss — recompute
  console.log("🔄 Cache miss — recomputing");
  const freshData = { result: "computed data" };
  cache = new WeakRef(freshData); // weak reference — won't prevent GC
  return freshData;
}

Profiling Memory in Chrome DevTools

Knowing the theory is half the battle. The other half is finding leaks in real apps. Chrome DevTools has excellent memory profiling tools — here's how to use them:

1
Open DevTools (F12 / Cmd+Option+I) → go to the Memory tab.
2
Select Heap Snapshot and click "Take Snapshot". This captures the current state of the heap — all live objects and their sizes.
3
Interact with your app (open/close modals, navigate routes, repeat an action several times). Then take a second snapshot.
4
In the second snapshot, change the filter dropdown from "All objects" to "Objects allocated between snapshots". Objects shown here were created and not freed — potential leaks.
5
Use the Allocation instrumentation on timeline mode to record memory over time. A constantly rising blue bar that never drops indicates a leak.
6
Click any suspicious object in the snapshot to see its Retainers — the chain of references keeping it alive. This pinpoints exactly which variable or closure is causing the leak.
Pro Tip
Before taking a snapshot, click the garbage collector icon (🗑) in the Memory panel to force a GC cycle first. This eliminates short-lived objects from your snapshot so you only see true long-term survivors.

Best Practices for Memory Efficiency

Apply these habits consistently and you'll rarely encounter memory issues in production:

Always use strict mode
'use strict' turns accidental globals into ReferenceErrors, catching the most common leak source at runtime.
Clean up timers & listeners
Always pair setInterval with clearInterval, and addEventListener with removeEventListener in cleanup/unmount hooks.
Null out references
When a large object (image buffer, API response) is no longer needed, set the variable to null explicitly so the GC can collect it.
Prefer WeakMap for caches
When caching data keyed by objects (DOM nodes, class instances), use WeakMap so entries are automatically removed when the key object is collected.
Avoid unnecessary closures
Extract only the primitive values you need from large objects before capturing them in a closure — don't let closures keep entire data sets alive.
Profile regularly
Add memory profiling to your development workflow — take heap snapshots after major user flows and compare them. Catch leaks before they reach production.
Advertisement

Try It Yourself

Live Editor
✎ Editor
👁 Preview
DevTools Challenge
Open Chrome DevTools → Memory tab → take a Heap Snapshot → click "Create Leak" a few times → take another snapshot → compare. You'll see the array growing in the retained objects list.
Quick Check — Chapter 64

Which garbage collection algorithm does modern JavaScript (V8) use as its foundation?

Chapter Summary
  • Memory follows a 3-phase lifecycle: Allocate → Use → Release. JS automates phases 1 and 3 via garbage collection.
  • Primitives (number, string, boolean…) live on the Stack; objects, arrays, and functions live on the Heap and are accessed by reference.
  • The Mark-and-Sweep algorithm walks all reachable objects from root, marks them alive, and sweeps the rest. V8 enhances this with a generational Young/Old heap split.
  • The four most common leaks: accidental globals, forgotten timers, detached DOM nodes, and closures over large data.
  • WeakMap and WeakSet hold weak references — their entries are auto-removed when the key object is collected. Use them for caches and DOM metadata.
  • WeakRef lets you hold a reference that doesn't prevent GC; call .deref() and handle the undefined case when the object was collected.
  • Profile with Chrome DevTools → Memory → Heap Snapshots; compare between-snapshot objects to find live leaks.

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel