Question presented to candidate: "What is a closure in JavaScript, and can you show me a case where getting them wrong causes a real, observable bug?"
What a strong answer should cover:
- A closure is a function bundled together with a live reference to the variables of the scope it was defined in, not a snapshot of their values at the moment it was created.
- That live reference survives even after the outer function has already returned and its call frame would otherwise be garbage collected.
- Two separate calls to the same outer function produce two fully independent closures with separate private state; two closures created from the SAME call share the exact same variable binding.
- The classic var-vs-let loop bug: closures created inside a var loop all share ONE binding and read whatever its final value ended up being, while let creates a fresh binding per iteration so each closure captures its own value.
- Closures are the mechanism behind private state (the module pattern), memoization/caching, and function factories.
Clarifying questions expected:
- "Do you want me to focus on closures specifically, or would it help to first cover how scope lookup works in general?" (lexical scoping is the broader mechanism closures are built on top of)
Code / implementation expected: Yes -- a short runnable snippet demonstrating the var-vs-let loop-capture difference with real observed output.