Skip to content
Concept 91 // Module 10: JavaScript Engine, Memory, Performance & Security

JavaScript Memory Model: Stack vs Heap

Module 10: JavaScript Engine, Memory, Performance & Security•Concept 91 of 100• 5 min read

JavaScript Memory Model: Stack vs Heap

The **Memory Model** defines how JS manages data in the **Stack** and **Heap**, and how the **Garbage Collector (GC)** reclaims unused memory. Mastering this is key to avoiding memory leaks and writing high-performance apps.

The Core Concept

Syntax Reference
// 1. Mark-and-Sweep (GC Strategy)
// If an object is not "reachable" from root, it is deleted.

// 2. Weak References
const ref = new WeakRef(myObj);
const realObj = ref.deref(); // null if GC'd

// 3. FinalizationRegistry
const registry = new FinalizationRegistry(held => {
  console.log("Cleaned up!", held);
});
registry.register(myObj, "metadata");

Live Interactive Studio

Closures are the most common cause of memory leaks. Even if you don't use `bigData`, the inner function keeps a reference to it in the Heap.
JavaScript Editor
Loading...
Console Output
Waiting for output...

Key Code Patterns in Action

01

Simple Memory Leak

// 1. Simple Memory Leak
function leak() {
  const bigData = new Array(1000000).fill("X");
  
  return function() {
    // Closure keeps bigData alive forever!
    console.log(bigData.length);
  };
}

const leakyFunc = leak();
Closures are the most common cause of memory leaks. Even if you don't use `bigData`, the inner function keeps a reference to it in the Heap.
02

Disconnected DOM Leak

// 2. Disconnected DOM Leak
let element = document.getElementById('button');

function cleanup() {
  document.body.removeChild(element);
  // 'element' variable still points to the DOM node!
  // GC cannot reclaim it until element = null;
}
Removing a node from the DOM isn't enough. If a JS variable still points to it, the engine keeps the entire DOM subtree in the Heap.
03

Generational GC (Orinoco)

// 3. Generational GC (Orinoco)
// Modern engines use "Generations"
// - Young Generation (new objects, fast GC)
// - Old Generation (survivors, heavy GC)
V8 uses a Generational Garbage Collector. Most objects die young. If an object survives two GC cycles, it's moved to the 'Old Space' which is scanned less frequently.
04

1. Core Usage: JavaScript Memory Model

// Core syntax and usage for JavaScript Memory Model: Stack vs Heap
const feature = 'javascript-memory-model-stack-vs-heap';
console.log('Concept 91:', feature);
console.log('Active:', true);
Illustrates the fundamental invocation and syntax structure for JavaScript Memory Model: Stack vs Heap.
05

2. Defensive Handling & Edge Case

// Edge-case defensive handling
function handleSafe(input) {
  if (input === null || input === undefined) return 'safe-fallback';
  return String(input).trim();
}
console.log(handleSafe('javascript-memory-model-stack-vs-heap'));
console.log(handleSafe(null));
Shows how to write defensive, safe JavaScript code that handles nullish or unexpected inputs when working with JavaScript Memory Model: Stack vs Heap.
06

3. Clean Architecture & Production Pattern

// Production-grade pattern for JavaScript Memory Model: Stack vs Heap
const settings = Object.freeze({
  id: 'javascript-memory-model-stack-vs-heap',
  ready: true,
  timestamp: Date.now()
});
console.log('Settings initialized:', settings.id, settings.ready);
Demonstrates clean, immutable production code avoiding unintended state mutations.

Real-World Engineering Takeaways

Performance Tuning: Reducing the frequency of 'Stop-the-world' GC pauses.
Memory Management: Using `WeakRef` for large caches that can be deleted under memory pressure.
Resource Cleanup: Using `FinalizationRegistry` to close file handles or socket connections.
App Stability: Identifying and fixing leaks in long-running Single Page Apps (SPAs).

Under the Hood: Engine & Memory Mechanics

How JavaScript Executes This
### **The Garbage Collector** **1. Reachability:** - The GC starts from "Roots" (Global object, current stack variables). - It "walks" the graph of pointers in **RAM**. Any object not reached is marked for deletion. **2. Scavenger (Young Gen):** - Uses a "Copying" algorithm. It splits memory into two semi-spaces and copies live objects to the new space while wiping the old one. This is extremely fast. **3. Major GC (Full Mark-Compact):** - Scans the entire **Heap**. - It moves objects together to eliminate "fragmentation" (holes in memory), ensuring contiguous space for the **CPU** to access.

Quick Knowledge Check

Test your understanding on these 10 questions (one by one):

Score: 0 / 10
Question 1 of 10 • Core Purpose & Mental Model

What is the core purpose of JavaScript Memory Model: Stack vs Heap in JavaScript?

// Concept 91: JavaScript Memory Model: Stack vs Heap
// Understanding the core mental model
1 / 10