MediumConcept

What is a closure in JavaScript and why is it useful?

Technology:
JavaScript
Experience:
Junior,
Mid-level

Quick answer

A closure is a function that keeps access to the variables of the scope where it was created, even after that outer function has finished running.

Detailed explanation

Every function in JavaScript carries a reference to the lexical environment it was defined in. When an inner function is returned or passed elsewhere, that environment stays alive for as long as the function can be called, so the inner function can still read and update the outer variables.

Closures give you private state without classes, power patterns such as memoization, debounce and once-only functions, and make callbacks and React hooks work. The trade-off is memory: anything captured by a closure cannot be garbage collected while the closure is reachable.

Example

javascript
function createCounter() {
  let count = 0;            // private, not reachable from outside
  return function () {
    count += 1;
    return count;
  };
}

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

Real-world example

Event handlers in a component often close over props or state. In React, a stale closure is why a setInterval callback can keep reading an old state value unless you use a functional update or a ref.

How to explain it in an interview

A closure is a function together with the variables from the scope where it was created. Because the inner function keeps a reference to those variables, they stay alive after the outer function returns. I use closures for private state, factories, memoisation and callbacks that need context, and I watch for the memory they keep alive.

Key points

  • A closure = a function plus its surrounding scope
  • Used for private state, factories, callbacks and memoization
  • Captured variables stay in memory while the closure is reachable

Common mistakes

  • Saying a closure copies values. It keeps a live reference, so later changes to the variable are visible inside the function.
  • Creating closures inside a loop with var and expecting each one to see a different index.
  • Ignoring memory: a long-lived closure keeps everything it references from being garbage collected.

Follow-up questions

  • Why does a loop with var and setTimeout print the same number?
  • How can closures cause memory leaks?
  • JavaScriptEasy

    What is hoisting in JavaScript?

    Hoisting is JavaScript moving declarations to the top of their scope during compilation, so functions and var variables can be referenced before the line where they are written.

    Intern · Junior · Functions & Scope
  • JavaScriptMedium

    How does the this keyword work in JavaScript?

    this is decided by how a function is called, not where it is written: as a method it is the object before the dot, with new it is the new object, and arrow functions inherit it from the enclosing scope.

    Junior · Mid-level · Functions & Scope