Interview questions
Explain closures with a real use case
A frequently asked question — definition plus why it matters.
A closure is a function that retains access to variables from its lexical scope even after the outer function has returned.
Closures give you private variables in a language that has no `private` keyword.
Key concepts
1
A strong answer names a concrete use case: private state. Because the counter variable below is only reachable through the returned function, no other code can tamper with it — the module pattern is built on exactly this.
private state
2
Interviewers often follow up with the loop + var trap, so be ready to explain that each let iteration creates a fresh binding while var shares one.
loop + `var`varlet
javascript
function createWallet(initial) {
let balance = initial; // private
return {
deposit: (n) => (balance += n),
getBalance: () => balance,
};
}
const w = createWallet(100);
w.deposit(50);
w.getBalance(); // 150 — balance not directly accessible