JavaScript · The language round
How does garbage collection work and what causes memory leaks?
Short answer
JavaScript uses reachability-based garbage collection: memory is reclaimed when a value can no longer be reached from roots such as the global object or the current stack. Leaks happen when something still references data you no longer need.
Modern engines use mark-and-sweep. Starting from roots, the collector marks everything reachable, then frees the unmarked objects. You cannot force collection or free memory manually; you can only remove references.
Common leak patterns
- Global variables that keep large objects alive
- Timers or intervals that are never cleared
- Event listeners on long-lived elements that are never removed
- Detached DOM nodes retained by a JavaScript reference
- Closures that capture more data than the callback needs
- Unbounded caches that never evict entries
function attach(element) {
const handler = () => console.log("clicked");
element.addEventListener("click", handler);
return () => element.removeEventListener("click", handler);
}A closure itself is not a leak. It becomes one when a long-lived callback keeps a large object reachable after the feature is gone. WeakMap and WeakSet help when metadata should not extend an object's lifetime.
const cache = new WeakMap();
function store(node, data) {
cache.set(node, data);
}Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What does mark-and-sweep mean?
- 2Why can an event listener cause a memory leak?
- 3How does a WeakMap prevent a leak?
- 4How would you investigate a growing heap?
Say it in the interview
Garbage collection is based on reachability. The engine marks objects reachable from roots such as the global object or the call stack, then reclaims the rest. Leaks happen when something still references data we no longer need: uncleared timers, forgotten listeners, detached DOM nodes, or unbounded caches. I clean up subscriptions and timers, avoid unnecessary globals, and use WeakMap when metadata should not keep an object alive.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.