call(back)

What Is a Closure?

What is a closure?

Answer out loud in under a minute: a definition, one concrete example, and one pitfall or trade-off.

Hints

Hint 1

Have one line of code ready that shows it: a counter factory is the classic.

Solution

Show the approach

Answer

A function plus the variables of the scope it was created in. Those bindings stay alive after the outer function returns. A closure captures the binding, not a snapshot of the value, which is why a var loop counter is shared by every callback while let gives each iteration its own. Uses: private state (a counter factory), callbacks, and every utility like debounce and once.

Asked at