Frontend Developer interview question
What is a closure in JavaScript?
A closure is a function bundled with its lexical environment. It retains access to variables from the scope where it was created, even after that outer function returns.
Direct answer
What a strong answer covers
How it works
Every function in JavaScript captures the variables of the scope it was defined in by reference, not by value. The captured binding lives as long as the closure does, so a variable that would otherwise be garbage collected stays reachable, and a later change to that variable is visible to the closure. This is the mechanism behind module patterns, memoisation, event handlers, and most bugs involving loops and asynchronous callbacks.
Example
A click handler can close over an id; each handler needs its own binding so it does not accidentally use a later loop value. With var in a for loop every handler shares one binding and reads the final value; with let each iteration gets a fresh binding, so the handler for the third button logs 3 instead of the loop end.
Common mistakes
- Believing a closure copies the value at creation time.
- Capturing a large object in a long-lived callback and creating a memory leak.
- Explaining closures without mentioning that the outer function may have already returned.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.