Modules, errors and memory · senior
Garbage collection, WeakMap and WeakRef
JavaScript frees memory automatically: the garbage collector keeps everything reachable from roots (globals, the current call stack, closures still in use) and reclaims the rest with mark-and-sweep, so a leak is memory your code still keeps reachable by accident.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe notes
What you must know
- Reachability: the collector marks everything reachable from roots and frees the rest. Mark-and-sweep handles cycles; simple reference counting can't.
- V8 is generational: most objects die young. The young generation is collected often by a fast copying scavenger; the old generation by mark-compact. Much of the work is parallel, incremental or concurrent, but GC can still pause the main thread.
- JS-level leaks: global caches or Maps that only grow, closures that hold big data, listeners and timers never removed, subscriptions never cancelled.
- WeakMap and WeakSet hold keys weakly: when nothing else references a key object, its entry can disappear. That is why they can't be iterated.
- WeakRef holds an object weakly; deref() may return undefined after collection. FinalizationRegistry runs a callback some time after an object is collected, or never. MDN says to avoid them where possible and never use them for essential logic.
- You can't force GC from page code. DevTools has a 'collect garbage' button; Node has --expose-gc.
The red pen
Common traps: mistake → fix
Mistake: JavaScript has a GC so leaks can't happen
Fix: reachable-but-unneeded memory is a leak.
Mistake: The GC uses reference counting
Fix: modern engines trace reachability, so cycles are fine.
Mistake: FinalizationRegistry works like a destructor
Fix: it may run late or never.
Easy to hard
Questions interviewers ask, easy to hard
- How does garbage collection work at a high level?
- What is a memory leak in JavaScript? Give three examples.
- Why can't you iterate a WeakMap?
- What are WeakRef and FinalizationRegistry, and why does MDN say to avoid them?
- How does V8's generational GC work, and why can long GC pauses hurt INP?
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.