JavaScript Interview Question Explain Garbage Collection
How to answer the garbage collection question: memory is freed when values become unreachable from roots. See mark and sweep, leaks, WeakMap and WeakRef.

Garbage collection is an interview question where the candidate cannot show a result on screen, since a collector runs when the engine decides and not when you ask. That makes it a question about concepts, and the interviewer is listening for three things: that you know JavaScript frees memory automatically, that you can say what counts as garbage, and that you know the ways a program still leaks memory. The good answer centers on one word, reachability. A value stays in memory as long as something that is still in use can reach it, and it becomes eligible for collection when nothing can. This post gives the answer in thirty seconds, then how the collector decides, the cases that cause leaks with code you can check, the weak references that let you opt out, and the wrong answers to avoid. The examples run on Node.js 24, and none of them depends on when the collector runs.
The answer in thirty seconds
JavaScript manages memory for you. When you create an object, array, string or function, the engine allocates memory for it, and when it is no longer needed, a garbage collector frees it. "No longer needed" is decided by reachability: starting from a set of roots, such as global variables and the current call stack, the collector follows references and marks everything it can reach. Anything it cannot reach is garbage, and its memory is reclaimed. You never free memory by hand, and you cannot force a collection from normal code.
let user = { name: "Ada", tags: ["a", "b"] };
const alias = user;
user = null;
console.log(alias.name);
alias.tags = null;
console.log(alias.tags);Ada
nullAfter user = null, the object is still reachable through alias, so it stays alive and alias.name works. If alias also went away, nothing would reach the object, and it would become garbage. Setting alias.tags to null made the array unreachable from that object, so the array is now eligible for collection even though the object is not. The engine does not run the collector at those lines, and the program cannot observe the moment: the code only shows that references determine what stays alive.
How the collector decides: mark and sweep
The standard algorithm has two phases. The mark phase starts at the roots and follows every reference, marking each object it visits. The sweep phase frees every object that was not marked. This handles cycles, which defeated an older idea called reference counting.
function makeCycle() {
const a = { name: "a" };
const b = { name: "b" };
a.other = b;
b.other = a;
return a.other.other === a;
}
console.log(makeCycle());trueThe two objects point at each other, so each has a reference to it for as long as the other exists. With reference counting, neither count would ever reach zero and the memory would leak. With mark and sweep, once the function returns and nothing outside can reach a or b, the collector never marks them, and both are freed together. Cycles are not a leak in JavaScript.
The generational idea
Most objects die young: a temporary array in a loop, a result object that is used once. Engines such as V8 exploit this by splitting the heap into generations. New objects go into a small young space that is collected often and quickly. Objects that survive a couple of collections are moved to an old space, which is collected less often, because scanning it is more expensive. Much of the work is done incrementally and concurrently with the program to avoid long pauses. For an interview, it is enough to say that collection is generational, that young objects are cheap to collect, and that long-lived objects cost more to scan.
const usage = process.memoryUsage();
console.log(Object.keys(usage));
console.log(typeof usage.heapUsed, usage.heapUsed <= usage.heapTotal);[ 'rss', 'heapTotal', 'heapUsed', 'external', 'arrayBuffers' ]
number trueprocess.memoryUsage() reports the heap that the collector manages, heapUsed and heapTotal, and memory outside it, such as buffers. We do not print the values, since they differ every run. The useful habit is to watch heapUsed over time in a long-running process: a figure that keeps rising after the work is done is the symptom of a leak.
How leaks still happen
A leak in JavaScript means memory that is reachable but no longer useful. The collector is correct, and the program is keeping a reference by mistake. Four causes cover most cases.
The first is a collection that only grows.
const cache = new Map();
function lookup(key) {
if (!cache.has(key)) cache.set(key, { key, big: new Array(10).fill(key) });
return cache.get(key);
}
for (let i = 0; i < 5; i++) lookup(`item-${i}`);
console.log(cache.size);
function makeBoundedCache(limit) {
const store = new Map();
return {
set(key, value) {
store.set(key, value);
if (store.size > limit) store.delete(store.keys().next().value);
},
size: () => store.size,
};
}
const bounded = makeBoundedCache(3);
for (let i = 0; i < 5; i++) bounded.set(i, i);
console.log(bounded.size());5
3A module-level Map is a root: everything in it stays reachable for the life of the program. The first cache has five entries and would have a million entries after a million different keys. The second removes the oldest entry past a limit, so its size stays at three. A cache without a bound is the most common leak we see.
The second is listeners that are never removed.
import { EventEmitter } from "node:events";
const bus = new EventEmitter();
function subscribe() {
const handler = () => {};
bus.on("tick", handler);
return () => bus.off("tick", handler);
}
const unsubscribers = [subscribe(), subscribe(), subscribe()];
console.log(bus.listenerCount("tick"));
unsubscribers.forEach((off) => off());
console.log(bus.listenerCount("tick"));3
0Each registered handler is reachable from the emitter, and so is everything the handler's closure captured. A component that subscribes on creation and never unsubscribes leaks one handler per instance. Returning an unsubscribe function, as above, makes the cleanup visible.
The third is timers that keep running. A setInterval keeps its callback, and everything the callback references, alive until clearInterval is called. The fourth is closures that hold more than you meant.
function createReader() {
const bigData = new Array(1000).fill("x");
return {
length: () => bigData.length,
};
}
const reader = createReader();
console.log(reader.length());1000The returned function uses bigData, so the array stays alive as long as reader does. That is correct here, and becomes a leak when a long-lived object holds a closure over data that is only needed briefly. Engines keep only the variables a closure actually uses, but what it uses stays.
Weak references
WeakMap and WeakSet hold their keys weakly: an entry does not keep its key alive. When the key object is otherwise unreachable, the entry can disappear with it.
const privateData = new WeakMap();
class Counter {
constructor() {
privateData.set(this, { count: 0 });
}
increment() {
const data = privateData.get(this);
data.count += 1;
return data.count;
}
}
const counter = new Counter();
console.log(counter.increment(), counter.increment());
console.log(privateData.has(counter), typeof privateData.size);
try {
privateData.set("text", 1);
} catch (e) {
console.log(e.name);
}1 2
true undefined
TypeErrorThe data is tied to the instance: when counter is unreachable, its entry can be collected, so a WeakMap is a good place for metadata about objects you do not own, such as a cache keyed by DOM node or by request. Because entries can vanish at any time, a WeakMap has no size, cannot be iterated and accepts only objects as keys. WeakRef holds a weak reference to one object.
const target = { id: 1 };
const ref = new WeakRef(target);
console.log(ref.deref() === target);
console.log(typeof FinalizationRegistry);true
functionRight after creation, within the same turn of the event loop, deref() returns the object, since the engine keeps a WeakRef target alive until the end of the current job. Later it may return undefined if the object was collected, and that timing is not specified. A FinalizationRegistry lets you run a callback after an object is collected, with the same caveat. The specification itself advises against depending on either for program correctness, so use them for caches and diagnostics only, never for releasing resources that must be released, which belongs in using or finally.
Finding a leak
The method is to measure, not guess. Run the process, exercise the suspect feature repeatedly, and take heap snapshots in Chrome DevTools or with node --inspect. Compare two snapshots and look at which objects grew in number. Objects retained by a surprising path point to the reference that holds them. A rising heapUsed over many cycles of the same work is the signal, and a single high reading is not.
Wrong answers that lose the point
"JavaScript has no memory leaks because it has garbage collection." The collector frees unreachable memory, and a reachable-but-unused object is a leak.
"Setting a variable to
nullfrees the memory." It removes one reference; the object is freed only if nothing else reaches it, and later."Circular references cause leaks." Mark and sweep handles cycles.
"You can call the garbage collector." Not from standard code; Node.js exposes
global.gconly with a flag, for testing.
A mistake we hit: a global registry of request objects
const requests = [];
function handle(request) {
requests.push(request);
return `handled ${request.id}`;
}
console.log(handle({ id: 1, body: "..." }));
console.log(handle({ id: 2, body: "..." }));
console.log(requests.length);
const activeIds = new Set();
function handleTracked(request) {
activeIds.add(request.id);
try {
return `handled ${request.id}`;
} finally {
activeIds.delete(request.id);
}
}
console.log(handleTracked({ id: 3 }), activeIds.size);handled 1
handled 2
2
handled 3 0A debugging array that stored each request "for later inspection" stayed in the code, and the process grew until it was restarted. The first design keeps every request forever. The second keeps only the small id, and only while it is needed, and the finally guarantees removal. The rule we follow is that anything stored in a module-level collection needs a removal path, and a size limit if the removal depends on events that might not happen.
Choosing between the approaches
| You need | Use |
|---|---|
| A cache that must not grow forever | A bounded cache, or a WeakMap keyed by objects |
| Metadata attached to objects you do not own | A WeakMap |
| An event subscription | An unsubscribe function, called on teardown |
| A timer | clearInterval or clearTimeout on teardown |
| A resource to release | using, or try ... finally |
| To watch memory | process.memoryUsage() and heap snapshots |
Practical rules we follow
Give every module-level collection a size limit or a removal path. Unsubscribe and clear timers on teardown. Use WeakMap for metadata keyed by objects. Do not depend on WeakRef or finalizers for correctness. Look for retention by closures when a long-lived object holds callbacks. And measure with heap snapshots before changing code.
Where the garbage collection answer stops being enough
A deeper question covers V8's collectors by name, Scavenge for the young generation and Mark-Compact for the old one, write barriers, incremental and concurrent marking, and tuning with flags such as --max-old-space-size. It may also cover memory in the browser, where detached DOM nodes are a classic leak. The answer above covers the concepts. The reference is in the MDN memory management guide and the V8 blog on the garbage collector.


