Lesson 24 of 80
JavaScript frees memory automatically based on one question — is this reachable? — and every 'memory leak' in JS is really just something staying reachable longer than you meant it to.
14 min read
Every option explains itself — why the right one is right, and why each wrong one is wrong. Miss one and it comes back later on a spaced-repetition schedule.
Question 1 of 2
What single question does JavaScript's garbage collector actually ask to decide whether to free an object?
Hints without spoilers, and a plain explanation of why a wrong answer was wrong — answered only from this lesson. Free account, no card.
Sign up freeWhat interviewers actually ask about this, and what a strong answer has to cover.
A strong answer covers
Likely follow-ups
JavaScript doesn't ask "is this variable out of scope" — it asks "can this object still be reached, starting from something the program can directly access (globals, the current call stack)?" If yes, it's kept. If no, the garbage collector reclaims it. A "memory leak" in JS isn't a low-level bug like in C — it's always an object staying reachable when you didn't intend it to be.
function attachListener() {
const hugeData = new Array(1_000_000).fill("x");
document.getElementById("btn").addEventListener("click", () => {
console.log(hugeData.length); // this closure keeps hugeData reachable
});
}
As long as that click listener is attached, hugeData stays reachable through the closure — even though attachListener itself finished running long ago. Remove the listener (or the element), and hugeData becomes reclaimable.
The GC asks one question about every object: can it still be reached from a root — globals, the call stack?
window) but never removed keeps everything its callback closes over reachable forever — this is the single most common real-world JS leak.Map used as a cache that only ever adds entries, never removes old ones, will grow indefinitely — this is exactly the problem WeakMap (previous lesson) solves when the key is an object."Find the memory leak in this code" is a real, common exercise — recognizing forgotten listeners and over-capturing closures as reachability problems (not vague "bad code") is what separates a correct diagnosis from a guess.