You said:

Explain what a closure is in JavaScript.

The assistant said:

A closure is a function that keeps access to the variables of the scope where it was created, even after that scope has returned.

JavaScript
function counter() {
  let count = 0;
  return () => ++count;
}

const next = counter();
next(); // 1
next(); // 2

Each call to counter() makes a new count, so two counters never share state.

You said:

When would I use one?

The assistant said:

Use a closure when a function needs private state:

  1. Counters and IDs that should not be global.
  2. Event handlers that remember their element.
  3. Factories that return configured functions.

Latest response