Interview questions

Explain closures with a real use case

A frequently asked question — definition plus why it matters.

intermediate All levels

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