mediumConceptCodingEntryMidSenior
What is a closure, and how does one end up leaking memory?
4 min readUpdated 2026-08-15
Answer
Short answer
A closure is a function plus the scope it was created in, held by reference rather than copied.It leaks when something long-lived keeps the function alive, because everything the captured scope can reach stays reachable with it.
Keep closures explicit in the answer because that is the concept the interviewer is actually trying to test. A good closures explanation names the trade-off, the failure mode, and the evidence you would use before choosing.
Was this answer helpful?
Likely follow-ups
- Two callbacks are created side by side and only one of them is stored. What could still be retained, and how would you check?
- Why does removeEventListener with an inline arrow function fail to remove anything?
- When would you reach for WeakMap or WeakRef, and what does each one not guarantee?
- How does a closure over a DOM node keep an entire detached subtree alive?
Related questions
- How is `this` determined in JavaScript, and why does a method lose it when you pass it as a callback?mediumAlso on javascript4 min
- Why do the functions you build inside a loop all end up returning the last value?mediumAlso on closures5 min
- How do goroutines leak, and how would you find a leak in a running service?mediumAlso on memory-leaks5 min
- Here is a script mixing setTimeout, a promise chain and an await. Tell me the order the logs come out in, and why.mediumAlso on javascript4 min