Functions & Closures

Closures

Functions remember the variables in scope when they were created.

js
function counter() {
  let n = 0;
  return () => ++n;
}

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

The inner arrow keeps n alive because it still references it. This is the building block for module patterns, memoization, and event handlers.

Interview questions

Sign in to save

What is a common memory pitfall with closures?

Long-lived closures can pin large scopes in memory. Only capture what you need, especially inside event listeners on removed DOM nodes.

Practice

Implement `once(fn)` so `fn` runs at most one time and later calls return the first result.

`this` binding