What is a closure? Explain the classic loop-with-setTimeout bug.
Closure literacy separates people who use JS from people who understand it. Every JS interview has some form of this.
Closure: a function plus the lexical environment it was created in. It "closes over" variables from that environment.
Scope chain: when resolving a name, JS walks from innermost scope outward through the chain of lexical environments.
Classic bug: `for (var i=0; i<3; i++) setTimeout(()=>console.log(i))` logs 3,3,3 — var is function-scoped, all callbacks share the same i.
Fix: use let (block-scoped, fresh binding per iteration) or IIFE to capture the current value.
Memory: closures hold references; if a closure outlives its scope, captured variables can't be GC'd. Common leak source.
A closure is a function paired with the scope where it was born — it keeps access to those variables even after the outer function returns. The classic test: var-based for loop setting setTimeout callbacks. Because var is function-scoped, all three callbacks reference the same i, which is 3 by the time they run — so 3,3,3. Swap for let and each iteration gets its own binding, so you get 0,1,2. I use this pattern intentionally when I need data privacy — expose only methods that close over private state instead of attaching to an object. The memory footnote: a DOM node held inside a closure that outlives the node is a classic leak, easy to create with addEventListener.
ES6 modules give you privacy for free — closures for privacy are less needed today but still show up in libraries.
Chrome DevTools → Memory → Heap snapshot shows closures as their own category — invaluable for leak hunting.
HireMe AI (即答侠) curates the top-5 closure gotchas so you recognize them by shape during interviews.
Technically yes — every function captures its lexical environment. In practice we call it a "closure" only when that capture matters, i.e., the outer scope has gone away.
Same scope semantics. The difference is `this` binding (arrow inherits, regular has its own) and arguments/new.target availability.
HireMe AI listens to your interview in real-time, detects questions, and generates instant answer suggestions — so you never freeze up again.
Try HireMe AI Free