Skip to content
jshacks.dev
Fundamentals

Memory Management in JavaScript Stack Heap and References

JavaScript manages memory for you, but what you keep decides how much is used. See stack and heap, shared references, clearing arrays and typed arrays.

8 min read
Summarize in AI
Flat illustration of a rising bar chart and a gauge, with the JavaScript, Prometheus, Redis, NGINX and npm logos.

You do not allocate or free memory in JavaScript, and it is still your job to know where memory goes. The engine puts data in a few places with different costs and lifetimes, and the choices you make, what you keep, what you copy and which container you use, decide how much a program needs and how long it holds it. This post builds a working picture of the stack, the heap and external memory, shows how references let large data be shared cheaply, and works through the habits that follow: clearing and reusing arrays, using typed arrays for numeric data, measuring instead of guessing. Output is from Node.js 24 as an ES module and avoids printing exact sizes, because those change between engine versions. The collector that frees memory is explained in the post on garbage collection, and the value-versus-reference rule is in the post on primitives versus objects.

Stack, heap and external memory

The picture has three areas. The call stack holds one frame per active function call, with its local variables and return address, and it shrinks as calls return. The heap holds objects, arrays, functions, closures and most strings, with a lifetime decided by reachability. External memory holds buffers and other data that the engine hands to the operating system directly, such as the contents of a Buffer or a typed array.

JavaScript
const base = process.memoryUsage();

const objects = Array.from({ length: 200_000 }, (_, i) => ({ id: i, label: "item" + i }));
const afterObjects = process.memoryUsage();

const bytes = new Float64Array(1_000_000);
const afterBytes = process.memoryUsage();

console.log(afterObjects.heapUsed - base.heapUsed > 1_000_000);
console.log(afterBytes.heapUsed - afterObjects.heapUsed < 1_000_000);
console.log(afterBytes.arrayBuffers - afterObjects.arrayBuffers >= bytes.byteLength);
console.log(bytes.byteLength, objects.length);
Text
true
true
true
8000000 200000

The array of objects grew the managed heap by more than a megabyte, since every object has a header and its own storage. The typed array did not grow the heap noticeably: its eight million bytes showed up in arrayBuffers, which counts memory outside it. The exact figures depend on the engine, and the relationships hold. A process can use a lot of memory while its JavaScript heap stays small, which surprises people who watch heapUsed alone.

References share, they do not copy

Passing an object to a function, or assigning it to another variable, copies a reference of a few bytes and not the data. That is why handing a ten-million-item array to a function costs nothing, and why the function can change it.

JavaScript
const big = Array.from({ length: 1_000_000 }, (_, i) => i);

function first(list) {
  return list[0];
}

function clear(list) {
  list.length = 0;
}

function replace(list) {
  list = [];
  return list.length;
}

console.log(first(big), big.length);
console.log(replace(big), big.length);

const alias = big;
clear(alias);
console.log(big.length, alias === big);

let working = [1, 2, 3];
const holder = working;
working = [];
console.log(working.length, holder.length);
working = holder;
working.length = 0;
console.log(holder.length);
Text
0 1000000
0 1000000
0 true
0 3
0

The function read the first element without any copy. The function that reassigned its parameter created a new array and left the caller's untouched. The function that set length to zero emptied the shared array, so the alias and the original both saw it. The last block repeats the contrast: reassigning working left holder with its three items, and setting length on the shared array cleared it for both names. This is the reason arr = [] and arr.length = 0 are different operations, and why clearing a buffer that other code holds must use the second.

Choosing a container for numbers

A plain array of numbers carries per-element overhead and a growth margin, and an array that mixes types or has holes is stored in a slower, larger form. A typed array stores exactly the bytes you ask for.

JavaScript
const count = 1_000_000;

const typed = new Float64Array(count);
const small = new Uint8Array(count);
const wide = new Float64Array(count * 4);

console.log(typed.byteLength, small.byteLength, wide.byteLength);

const before = process.memoryUsage().heapUsed;
const plain = new Array(count).fill(0);
const after = process.memoryUsage().heapUsed;
console.log(after - before > 0, plain.length);

const mixed = [1, "two", { three: 3 }, null];
const holey = [1, , 3];
console.log(mixed.length, holey.length, 1 in holey);

typed[0] = 0.1;
small[0] = 300;
console.log(typed[0], small[0]);
Text
8000000 1000000 32000000
true 1000000
4 3 false
0.1 44

The sizes of the typed arrays are the element size times the length, with no overhead per item, and the byte array is an eighth of the size of the double array. The plain array grew the heap. Typed arrays also enforce one type, so the second assignment wrapped 300 to 44, covered in the post on typed arrays. Use them for large numeric data, such as measurements, pixels and audio, and keep ordinary arrays for mixed or small collections, where the difference is invisible.

Strings and sharing

Strings are immutable, so the engine can share and slice them freely. Concatenation in a loop is cheap on modern engines, because they represent the result as a tree of pieces and flatten it on demand. A very long string held for its whole life, or a small substring that keeps a large parent alive in some engines, is where memory behavior can surprise you.

JavaScript
let text = "";
for (let i = 0; i < 100_000; i++) text += "line " + i + "\n";
console.log(text.length);

const lines = text.split("\n");
console.log(lines.length, lines[0], lines.at(-2));

const parts = [];
for (let i = 0; i < 100_000; i++) parts.push("line " + i);
console.log(parts.join("\n").length === text.length - 1);

const slice = text.slice(0, 20);
console.log(slice.length, JSON.stringify(slice));
Text
1088890
100001 line 0 line 99999
true
20 "line 0\nline 1\nline 2"

The loop built a large string without trouble, and the array-and-join form produced the same text. Both are fine for ordinary sizes. If you extract a small piece of a huge string and keep only the piece, copying it into a fresh string, with a technique such as String(piece) or a regex match, avoids holding the parent in engines that share storage, though that is an engine detail and not a language guarantee. Measure before changing code for it.

Clearing and reusing data

Holding memory longer than needed is the usual cost. Three habits help.

JavaScript
const buffer = [];

function fill(n) {
  for (let i = 0; i < n; i++) buffer.push({ i });
}

fill(1000);
console.log(buffer.length);

buffer.length = 0;
console.log(buffer.length);

fill(10);
console.log(buffer.length);

const cache = new Map([["a", { big: new Array(1000).fill(1) }]]);
cache.delete("a");
cache.clear();
console.log(cache.size);

let temporary = { payload: new Array(1000).fill(2) };
const view = temporary.payload.length;
temporary = null;
console.log(view, temporary);
Text
1000
0
10
0
1000 null

Emptying a long-lived array with length = 0 releases its elements while keeping the array identity, which suits a reusable buffer. Deleting from a map drops the entries. Setting a variable to null removes one reference and does nothing if another still exists, and in a short function it is unnecessary, since the variable dies on return. Setting to null matters in two places: long-lived variables such as a module-level cache or a field on a long-lived object, and a variable captured by a closure that outlives its purpose.

Object shapes and element kinds

V8 optimizes objects that have the same shape, meaning the same properties added in the same order, and arrays that hold one kind of element. Creating objects with a consistent shape, initializing all fields in the constructor and avoiding delete, keeps them on the fast path and uses less memory than dictionary-mode objects. The effect is not visible in correctness, and it is visible in large collections of records, where a constructor-built class instance is a compact, predictable record and a bag of ad hoc properties is not.

JavaScript
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}

const points = Array.from({ length: 5 }, (_, i) => new Point(i, i * 2));
console.log(points.map((p) => Object.keys(p).join("")).join(" "));

const adhoc = {};
adhoc.x = 1;
adhoc.y = 2;
delete adhoc.x;
console.log(Object.keys(adhoc));

const ordered = [1, 2, 3];
ordered.push(4.5);
ordered.push("five");
console.log(ordered);
Text
xy xy xy xy xy
[ 'y' ]
[ 1, 2, 3, 4.5, 'five' ]

The class gave every instance the same fields in the same order. The ad hoc object lost a field with delete, which pushes engines toward a slower representation. The array started with small integers, gained a double and then a string, and each change moves it to a more general storage kind. None of this is a rule to follow blindly. It explains why a million records built the same way are cheaper than a million built in many different ways, and it is the first thing to check when a large collection is slow or large.

Measuring instead of guessing

A memory question deserves a measurement. process.memoryUsage() and v8.getHeapStatistics() give figures from code, heap snapshots show what is on the heap by type and the --heap-prof flag samples allocations. Measure in a loop with a forced collection when you must compare, and repeat, since one reading is noisy. Compare a before and after of the specific change, and be suspicious of any claim that a technique "saves memory" without both numbers and the hardware.

JavaScript
const reading = () => Math.round(process.memoryUsage().heapUsed / 1_000_000);

const first = reading();
const kept = Array.from({ length: 300_000 }, (_, i) => ({ id: i }));
const second = reading();

console.log(second >= first, kept.length);
console.log(typeof globalThis.gc === "function" ? "gc available" : "no gc flag");
Text
true 300000
no gc flag

The reading went up as the objects were allocated, and the program could not force a collection without the flag. In a test of a leak fix, run Node.js with --expose-gc, call gc() before each reading and compare readings across several iterations.

Where this advice stops

Most programs never need to think about memory beyond not keeping what they do not need. The cases that do are long-lived servers, large datasets in the browser, and tools that process big files. For those, the order of attack is stable: find what is retained, with snapshots, before changing data structures, since a leak dwarfs any per-object saving. Only then consider typed arrays, streaming instead of loading, and pooling.

The behavior is described in the Node.js documentation for process.memoryUsage() and the v8 module, and MDN's guide to memory management covers the model.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.