learn deep. ship safe.Practice testsFollow ByteMunSubscribe

Concept

Closures

A function that keeps access to the variables of the scope it was created in, after that scope has finished.

Closures explained

A closure is a function that remembers the variables of the place where it was created, even after that outer function has finished running. In JavaScript every function is a closure: it carries a link to its surrounding scope, not a copy of the values. That is why a function returned from another function can still read and change the outer variables later.

How a closure works

When makeCounter runs, it creates count. The inner function keeps a reference to that variable, so each call to the returned function sees the same count, and nothing outside can reach it directly.

function makeCounter() {
  let count = 0;
  return function next() {
    count += 1;
    return count;
  };
}

const counter = makeCounter();
counter(); // 1
counter(); // 2 — the same count, kept alive by the closure

Call makeCounter() again and you get a second, independent count. This is how closures give you private state without classes.

Where you use closures every day

  • Event handlers and callbacks that read a variable from the code that set them up.
  • React hooks: every render creates new functions that close over that render's props and state.
  • Factories and modules that hide internal state and expose a few functions.
  • Memoization: a cache object kept alive inside a wrapper function.

Common mistakes

  • The var loop bug. for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)) prints 3 three times, because all callbacks share one i. With let, each iteration gets its own binding and it prints 0, 1, 2.
  • Stale closures in React. An effect or interval that captured an old state keeps using it. Add the value to the dependency array, or use the functional update form setCount(c => c + 1).
  • Accidental memory retention. A long-lived callback that closes over a large object keeps that object in memory. Remove listeners and clear timers you no longer need.

What interviewers ask about closures

  • "What will this loop print?" Explain shared var versus per-iteration let.
  • "Implement a function that can only be called once." Keep a called flag and the result inside a closure.
  • "How would you make a private variable?" Return functions that close over it, as in the counter above.
  • "Does a closure copy the value?" No. It keeps a reference to the variable, so later changes are visible.
Concept map
Part of JavaScriptClosures
Then learnReact hooks

What should you learn before Closures?

  1. FunctionsReusable blocks of code; in JavaScript they are values that can be passed around and returned.
  2. Variables and scopeClosures are functions remembering their scope, so scope comes first.

What to learn after Closures

Connections to other concepts

Part of
JavaScript

Practise Closures

All topics