Node.js · Senior · Question 5 of 75
Why can a closure cause unexpected memory retention?
function handler(req) {
const hugeBody = req.body; // 50 MB
const id = hugeBody.id;
emitter.on("done", () => console.log(id));
}- ✓Correct answer: The listener lives on a long-lived emitter, and the closure keeps its scope (and possibly
hugeBody) alive for every request - 2Closures are always copied with the full call stack
- 3Arrow functions can't be garbage collected
Explanation
The real bug is the listener that is never removed. V8 may also keep variables of a shared context alive. Remove listeners, use once, and don't capture large objects.