Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up

What is a closure, and where would you actually use one?

A closure is a function together with the scope it was created in. When a function is defined inside another function, it keeps a live reference to the outer function's variables — even after the outer function has returned.

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

count survives because the returned function still refers to it.

Where you genuinely use them:

  • Private state. Anything the caller should not be able to reach directly — a cache, a counter, a configuration captured once.
  • Function factories. debounce and throttle both work by closing over a timer id.
  • Partial application. Capturing the first argument and returning a function that takes the rest.
  • Every React hook. useState and useEffect rely on closures, which is exactly why stale-closure bugs are the most common hooks mistake.

Note: Be ready for the follow-up on memory. A closure keeps its captured scope alive, so holding one in a long-lived structure keeps everything it captured from being collected.

All Javascript interview questions

Login to manage your account

Please enter a valid email address.
Forgot Password?
Please enter a valid password.
OR

Don't have an account yet? Sign up as