Sub topic 1
How JavaScript Allocates and Releases Memory
Every value your program creates takes up memory. JavaScript hides most of that work from you: you never ask for bytes and never hand them back. The engine still allocates and frees memory, though, and when you write code without a picture of that process you get pages that slow down over hours, Node.js servers that crash with "heap out of memory," and bugs that only show up in production. This chapter gives you that picture. The rest of the tutorial builds on it.
Prerequisites
This chapter assumes you can already:
- Declare variables and work with objects, arrays, and functions.
- Explain in rough terms what a closure is and how scope works.
- Use callbacks, timers such as
setInterval, and event listeners. - Run JavaScript in a browser console or with Node.js from a terminal.
You don't need any background in C, operating systems, or how compilers work.
The Three Stages of the Memory Lifecycle
Memory goes through the same three stages in every programming language:
- Allocate. The program reserves memory to hold a value.
- Use. The program reads and writes that memory.
- Release. The memory is returned so it can be reused.
Languages differ in who does each stage. In JavaScript the engine does stage 1 automatically whenever you create a value. You do stage 2 through ordinary code. A component of the engine called the garbage collector (GC) does stage 3 automatically. The GC is the part of the engine that finds memory the program can no longer use and reclaims it.
The gap between "Unreachable" and "Freed" matters. An object does not disappear the moment you stop using it. It becomes eligible for collection, and the GC reclaims it later on its own schedule.
Stage 1: Allocation Happens Implicitly
JavaScript has no malloc. Memory is allocated as a side effect of creating values, and that happens more often than the syntax makes obvious.
// Explicit-looking allocations
const point = { x: 1, y: 2 }; // a new object
const list = [1, 2, 3]; // a new array
const greet = function () {}; // a new function object
const now = new Date(); // a new Date instance
// Less obvious allocations
const label = "point: " + point.x; // a new string
const parts = "a,b,c".split(","); // a new array plus three new strings
const doubled = list.map((n) => n * 2); // a new array and a new arrow function
const copy = { ...point }; // a new object
const { x, ...rest } = point; // `rest` is a new object
function makeCounter() {
let count = 0; // kept alive by the closure below
return () => ++count; // a new function object on every call
}
const counter = makeCounter();
console.log(label, parts, doubled, copy, rest, counter(), now instanceof Date);The table lists common sources of allocation, including ones that are easy to miss.
| Code | What gets allocated |
|---|---|
| `{}`, `[]`, `new Foo()` | An object or array |
| `function () {}`, `() => {}` | A function object, and a scope for any variables it captures |
| `a + b` with strings | Usually a new string (engines may build a rope internally) |
| `arr.map`, `filter`, `slice`, `concat` | A new array |
| `{ ...obj }`, `[...arr]` | A shallow copy |
| `JSON.parse(text)` | A whole tree of objects, arrays, and strings |
| `arr.push(x)` past current capacity | A larger backing store; the old one becomes garbage |
| `async` functions and `await` | Promise objects and saved execution state |
Small numbers and booleans are a special case. Engines such as V8 can store small integers directly inside a value slot without a separate heap allocation. Chapter 2 covers how primitives and references are stored. For this chapter the rule is simple: if you create an object, array, function, or string, assume memory was allocated.
Stage 2: Using Memory
Using memory means reading and writing variables and properties. This stage needs no special care, with one point that later chapters depend on: assignment copies references to objects, not the objects themselves.
const original = { tags: ["a"] };
const alias = original; // no new object; two names for one object
alias.tags.push("b");
console.log(original.tags); // [ 'a', 'b' ]Here only one object exists, and two variables refer to it. The object stays alive as long as either variable can still reach it. This is the core of how the GC decides what to keep.
Stage 3: Release Is Automatic
In C, you release memory yourself:
#include <stdlib.h>
int main(void) {
int *numbers = malloc(100 * sizeof(int)); /* allocate */
if (numbers == NULL) return 1;
numbers[0] = 42; /* use */
free(numbers); /* release */
return 0;
}If you forget free, the memory leaks. If you call it twice, or use the pointer after freeing it, the program can crash or be exploited. JavaScript removes that whole class of bugs by not giving you a free at all.
| Row | Manual (C, C++ without smart pointers) | Automatic (JavaScript, Java, Python, Go) |
|---|---|---|
| Who releases memory | The programmer | The garbage collector |
| Use-after-free bugs | Possible | Not possible |
| Double free | Possible | Not possible |
| Leaks | Forgetting to free | Keeping references you no longer need |
| Timing of release | Exactly when you call `free` | Decided by the engine, not predictable |
| Runtime cost | Low, predictable | GC work and occasional pauses |
Leaks are in both columns. Automatic memory management prevents you from freeing too early. It does not stop you from holding on too long.
How the GC decides what is "no longer needed"
A perfect collector would free every value the program will never touch again. No algorithm can know that in general, because it depends on the program's future behavior. Engines use an approximation instead: reachability. A value is kept if the program can still get to it by following references from a fixed set of starting points, such as global variables and the local variables of functions currently running. Anything that cannot be reached is garbage.
let session = { user: "Ada", history: new Array(100_000).fill("event") };
let current = session;
session = null; // the object is still reachable through `current`
current = null; // now nothing reaches it; it is eligible for collectionThe approximation is safe in one direction only. An unreachable object can never be used again, so freeing it is always correct. A reachable object might never be used again either, but the GC must keep it anyway. Most JavaScript memory leaks come from this gap: data your code is done with that is still reachable through a forgotten timer, listener, closure, or cache. Chapter 3 defines roots and reachability precisely, and Chapter 7 catalogs the leak patterns.
Watching the Lifecycle Happen
You can see all three stages in Node.js. The --expose-gc flag makes a gc() function available so you can trigger a collection for demonstration. Use it only for experiments like this one, never in production code.
// Save as lifecycle.js and run: node --expose-gc lifecycle.js
const heapMB = () =>
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(1) + " MB";
global.gc();
console.log("baseline: ", heapMB());
// Allocate: one million small objects
let records = Array.from({ length: 1_000_000 }, (_, i) => ({ id: i }));
console.log("after allocation: ", heapMB());
// Use
let sum = 0;
for (const r of records) sum += r.id;
console.log("sum:", sum);
// Drop the only reference. The data is now unreachable but not yet freed.
records = null;
console.log("after records=null:", heapMB());
// Release: the collector reclaims the unreachable objects
global.gc();
console.log("after gc(): ", heapMB());Typical output looks like this. Exact numbers depend on your Node.js version and platform.
baseline: 3.6 MB
after allocation: 52.3 MB
sum: 499999500000
after records=null: 52.3 MB
after gc(): 3.9 MBThe third line is the one to study. Setting records to null frees nothing by itself. Heap usage drops only when the collector runs. In a real program the engine decides when that happens, based on allocation rate and heap size.
Common Misconceptions
"Setting a variable to null frees the object"
Assigning null removes one reference. If another reference exists, the object stays alive. If none exists, the object becomes eligible, and the GC frees it later. Assigning null is useful for long-lived variables that hold large data. For local variables inside a function that is about to return, it is usually pointless.
"`delete` frees memory"
delete removes a property from an object. It does not touch the value the property pointed to.
const store = { payload: new Array(1_000_000).fill(0) };
const kept = store.payload;
delete store.payload;
console.log("payload" in store); // false
console.log(kept.length); // 1000000, still alive through `kept`"Memory usage should go down right after I stop using data"
Heap graphs in DevTools or process.memoryUsage() usually show a sawtooth: usage climbs as you allocate and drops when the GC runs. A rising sawtooth is normal. A leak shows as a baseline that keeps rising: the low points after each collection keep getting higher. Chapter 9 shows how to tell these apart with heap snapshots.
"Garbage collection is free"
The collector does real work, and some of that work can pause your code. Allocating many short-lived objects in a hot loop makes the GC run more often. Modern engines reduce the cost with generational, incremental, and concurrent collection (Chapters 10 and 13), but allocation still has a price. Chapter 14 covers how to allocate less.
What Comes Next
You now have the model the rest of the tutorial uses. Allocation is implicit and frequent. Use goes through references. Release is automatic and happens at a time the engine chooses, for objects that are no longer reachable. The next chapters fill in each part: where values live (stack and heap), exactly what counts as reachable, and the algorithms engines use to find garbage.
Exercise
In the code below, after the last line runs, which of the two arrays is eligible for garbage collection? let a = [1, 2, 3]; let b = [4, 5, 6]; const holder = { item: a }; a = b; b = null;
Show answer
Neither array is eligible. The first array [1, 2, 3] is still reachable through holder.item. The second array [4, 5, 6] is still reachable through a, which was reassigned to point to it before b was set to null.
Exercise
A colleague runs delete cache.results on an object that holds a 200 MB array, checks process.memoryUsage().heapUsed right away, and sees no change. Give two separate reasons the number might not have dropped.
Show answer
First, the array may still be reachable through another reference, such as a variable or another object that also points to it, so it is not garbage at all. Second, even if cache.results was the last reference, delete only makes the array eligible for collection. The memory is reclaimed only when the garbage collector next runs, and that may not have happened yet.
Exercise
List every allocation in this line, assuming users is an array of objects with a name string property: const names = users.filter(u => u.active).map(u => u.name.toUpperCase());
Show answer
Two arrow function objects (one passed to filter, one passed to map), the intermediate array returned by filter, the final array returned by map, and one new string per active user from toUpperCase. The intermediate array from filter becomes garbage as soon as map finishes, because nothing keeps a reference to it.