Interview Questions
Closures · Study material
Closures – Interview Questions
1. What is a closure?
A function bundled with references to the variables of the scope in which it was created, so it can use them even after that scope's function has returned.
2. Give a practical use of closures.
Private state (counters, bank accounts), function factories (makeMultiplier), memoization caches, once, debounce/throttle, event handlers and callbacks that need context, and the module pattern.
3. Why does a for loop with var and setTimeout print the same number?
All callbacks close over the same function-scoped variable, which holds its final value when they run. let creates a new binding per iteration; an IIFE can copy the value.
4. Do closures capture values or variables?
Variables. A closure sees the current value when it runs, not the value at the moment it was created.
5. If a factory is called twice, do the returned functions share state?
No. Each call creates a new environment. Functions returned from the same call do share it.
6. How do closures provide data privacy?
Variables declared in the outer function are not reachable from outside; only the returned inner functions can read or modify them.
7. What is a stale closure?
A closure that uses an old value – because it captured a copy, or a variable that was later replaced – while the code expects the current one. Common with timers and React hooks.
8. Can closures cause memory leaks?
They keep their captured variables alive as long as the closure is reachable. Long-lived closures (listeners, intervals, caches) that capture large data can hold memory unnecessarily.
9. What is the module pattern?
An IIFE (or factory) that keeps private variables in a closure and returns an object exposing only the public API.
10. How is memoization implemented with closures?
A higher-order function creates a cache and returns a function that checks the cache before calling the original function.
11. Does a closure capture this?
Regular functions get this from the call, not from the closure. Arrow functions have no own this and use the this of the enclosing scope, so they effectively capture it.
12. What is debouncing and how do closures help?
Delaying a function until calls stop for a given time. The returned function keeps the pending timer id in a closure so it can cancel and restart it.
13. What is the difference between a closure and a callback?
A callback is a function passed to be called later; a closure is a function that remembers its outer variables. Callbacks are often closures.
14. How do you reset private state correctly?
Assign to the captured variable (count = 0). Declaring let count = 0 inside the reset function creates a new local variable and leaves the private one unchanged.
15. What does an IIFE have to do with closures?
An IIFE creates a new scope immediately; functions returned or created inside it close over that scope – used for private state and for copying loop values before let existed.