Tech Interview RoomStudy guides

JavaScript

What is a closure? Give a practical use.

Beginner · 2 min read · Lesson 2 of 12 in JavaScript

A closure is a function together with the variables from the scope it was created in. The inner function keeps access to those variables even after the outer function has returned, because the variables live in a heap-allocated environment, not on the call stack.

Why it matters

  • Data privacy: hide state that only exposed functions can change (the module pattern).
  • Function factories: build specialised functions such as multiplier(2).
  • Callbacks and event handlers remember the values they need.
  • Memoisation, debounce and throttle all keep their cache or timer in a closure.
  • React hooks rely on closures: every render creates new handler functions that close over that render's props and state.

Memory note

A closure keeps its whole captured scope alive. A long-lived closure, for example an event listener that is never removed, can keep large objects in memory and cause a leak.

Example

js
function createCounter() {
  let count = 0;                       // private: not reachable from outside
  return {
    increment: () => ++count,
    reset: () => { count = 0; },
    get value() { return count; },
  };
}

const counter = createCounter();
counter.increment();
counter.increment();
console.log(counter.value); // 2
console.log(counter.count); // undefined: the variable is hidden

Follow-up questions interviewers ask

Try answering each one before you open it.

What is a stale closure in React?

A handler or effect created during one render captures that render's state. If it runs later, for example inside a setInterval set up once in useEffect(..., []), it still sees the old value. Fixes: list the value in the dependency array, use the functional updater setCount(c => c + 1), keep the latest value in a useRef, or use useEffectEvent (React 19.2) for logic that must read fresh values without re-running the effect.