JavaScript · Question 1 of 50

What is a closure?

What they're checking

Whether you understand scope well enough to use it, not just define it.

The answer

A closure is a function together with the variables it could see where it was created. When an inner function is returned or passed somewhere else, it keeps access to those variables, the live variables and not a copy, even after the outer function has returned.

That is how you get private state without a class: a counter whose count nobody else can touch, a memoised function holding its cache, an event handler that remembers which item it belongs to.

function makeCounter() {
  let count = 0
  return () => ++count
}
const next = makeCounter()
next() // 1
next() // 2

The picture

makeCounter()               next()
┌───────────────┐  returns  ┌──────────────┐
│ let count = 0 │ ────────▶ │ ++count      │
│ return () =>  │           │ still sees   │
└───────────────┘           │ count        │
        ▲  scope stays alive └──────┬───────┘
        └───────────────────────────┘
The follow-up they'll ask

What does this print? for (var i = 0; i < 3; i++) setTimeout(() => console.log(i))

Show the answer

3, 3, 3. All three callbacks close over the same var i, which is 3 by the time they run. With let, each loop turn gets its own binding: 0, 1, 2.

Your progress stays on this device.