JavaScript interview question

What is a closure in JavaScript?

Short answer

A closure is a function bundled with the variables from the scope where it was created. The inner function keeps access to those variables even after the outer function has returned. Closures power private state, function factories, memoisation and callbacks, and explain classic bugs such as loops that capture a shared variable.

A minimal example

javascriptfunction makeCounter() {
  let count = 0;            // captured by the closure
  return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2

Common uses

  • Encapsulation — keep state private without classes.
  • Factories — create preconfigured functions such as makeLogger("api").
  • Memoisation — cache results inside a wrapper function.
  • Event handlers and callbacks that need values from their setup scope.

The loop pitfall

With var, every callback created in a loop shares one variable, so they all see its final value. Using let creates a fresh binding per iteration and fixes the problem.

How to answer it in an interview

  • Define it in one sentence first, then show the counter example.
  • Mention memory: closures keep captured variables alive, which can cause leaks if references are never released.
  • Link it to React: stale closures in useEffect are a frequent follow-up.

Walk into your next interview prepared

Start free, install the Windows app and run a practice session today.