Skip to content
jshacks.dev
Functions

Closures in JavaScript The Complete Guide With Real Uses

A complete guide to closures in JavaScript: scope, what a closure captures, loops, private state, stale values, memory leaks and real uses, with exact output.

29 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, Node.js and npm logos.

A closure is what you get when a function remembers the variables that were around it when it was created, and keeps using them after the code that created them has finished. That sentence sounds like a minor technical detail, and it is the mechanism behind a large share of everyday JavaScript: callbacks that still know which item they belong to, counters and caches with private state, event handlers, setTimeout calls, modules before modules existed, debounce and memoize helpers, React hooks and most of what people mean by "functional" style. It is also the source of a famous set of bugs, from the loop that logs the same number three times to the interval that keeps reading an old value. This guide builds closures from the ground up. It starts with scope, defines the term precisely, shows what the engine does, then goes through the real uses, the traps and the memory behavior, with exact output from Node.js 24 for every example. By the end you should be able to predict what any closure will do, and to say why.

Start with scope

To understand closures, first be clear about scope: the part of a program where a name can be used. JavaScript decides scope by where code is written, not by where it runs. That is called lexical scope, from the word for the text of the program, and it means that you can read a function and know which variables it can see without running anything.

JavaScript
const planet = "Earth";

function outer() {
  const country = "Norway";

  function inner() {
    const city = "Oslo";

    return `${city}, ${country}, ${planet}`;
  }

  return inner();
}

console.log(outer());
Text
Oslo, Norway, Earth

inner uses three names. city is its own. country belongs to outer, the function around it. planet belongs to the module, around both. When the engine meets a name, it looks in the current scope, then in the scope around it, then the next one out, until it finds the name or runs out of scopes and throws a ReferenceError. That ordered list of scopes is the scope chain. The lookup goes only outward: outer cannot see city, and the module cannot see country.

JavaScript
function outer() {
  const hidden = "inside";
}

outer();

try {
  console.log(hidden);
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
ReferenceError: hidden is not defined

Scopes in modern JavaScript come from three places: functions, blocks and the module or script itself. let and const are scoped to the nearest pair of braces, so a variable declared inside an if or a for body does not leak out of it. A var is scoped to the whole function, which is one of the reasons it is no longer used in new code. Everything in this guide uses let and const.

What a closure is

Normally, when a function finishes, its local variables are no longer needed, and they go away. A closure is the case where they are still needed, because a function that was created inside still refers to them.

JavaScript
function makeGreeter(greeting) {
  function greet(name) {
    return `${greeting}, ${name}!`;
  }

  return greet;
}

const hello = makeGreeter("Hello");
const bonjour = makeGreeter("Bonjour");

console.log(hello("Ana"));
console.log(bonjour("Bo"));
Text
Hello, Ana!
Bonjour, Bo!

makeGreeter returned a function and finished. Its parameter greeting should be gone. But hello("Ana") still prints Hello, so the returned function must still have access to it. That is the closure: the function greet together with the variable greeting from the scope where it was created. There are two closures here, one for each call to makeGreeter, and each has its own greeting. They do not interfere, since each call created a separate scope.

A precise definition is useful. A closure is a function bundled with a reference to its surrounding scope, its lexical environment. In JavaScript, every function is a closure, because every function remembers the scope where it was created. People use the word for the interesting case, where a function is used outside of the scope that created it, and the remembered variables matter.

What is captured: variables, not values

The most important fact about closures is also the one that people get wrong. A closure captures the variable itself, not a copy of its value at the moment the function was created.

JavaScript
function demo() {
  let message = "first";

  const show = () => message;

  message = "second";

  return show();
}

console.log(demo());
Text
second

show was created when message was "first", but it reads message when it is called, and by then the value is "second". The closure holds a live reference to the variable. This is the basis of private state, since a function can change a captured variable and other functions see the change, and the basis of the loop bug, as a later section shows.

JavaScript
function createCounter() {
  let count = 0;

  return {
    increment() {
      count += 1;
    },
    read() {
      return count;
    },
  };
}

const counter = createCounter();

counter.increment();
counter.increment();

console.log(counter.read());
Text
2

Both methods close over the same count. increment changes it and read sees the change, and nothing outside createCounter can reach count any other way: there is no property to read and no name to import. That is private state, built from nothing but a function and a variable.

How the engine does it

You do not need to know the internals to use closures, and a short mental model helps with the trickier cases. Each time a function runs, the engine creates an environment record, a table that holds the function's variables. It also links the record to the one of the scope around the function, which is the scope chain in data form. When a function object is created, it stores a hidden reference to the environment that is current at that moment.

When a function is called, its new environment record points at the stored one. Name lookup follows these pointers outward. If no function created inside still holds a reference to an environment record, the garbage collector can free it when the call ends. If an inner function does hold a reference, as greet does to the record of makeGreeter, the record stays alive for as long as that function does.

That explains two behaviors. First, a closure costs memory: the record and everything in it stay reachable while the function is reachable. Engines are smart about this, and V8, for example, keeps only the variables that inner functions actually use in the context that closures share, but you cannot count on the details. Second, every call makes a new record, so each call to a function that returns a closure gets an independent copy of the state, as the greeters showed.

Closures in loops

The loop is where most people first meet closures, usually as a bug.

JavaScript
const callbacks = [];

for (var i = 0; i < 3; i++) {
  callbacks.push(() => i);
}

console.log(callbacks.map((fn) => fn()));
Text
[ 3, 3, 3 ]

A var belongs to the enclosing function, so there is one i, shared by all three arrow functions. They capture the variable, not its value at each pass, and by the time they run, the loop has finished and i is 3. With let, the loop creates a fresh binding for each iteration.

JavaScript
const callbacks = [];

for (let i = 0; i < 3; i++) {
  callbacks.push(() => i);
}

console.log(callbacks.map((fn) => fn()));
Text
[ 0, 1, 2 ]

Each pass has its own i, and each arrow captured its own. In code that must use var, the older fix is a function that creates a scope per pass, called immediately.

JavaScript
const callbacks = [];

for (var i = 0; i < 3; i++) {
  callbacks.push(
    ((captured) => () => captured)(i),
  );
}

console.log(callbacks.map((fn) => fn()));
Text
[ 0, 1, 2 ]

The outer arrow takes i as a parameter, so captured is a new variable holding a copy of the value, and it returns the inner arrow that closes over that copy. The same bug happens with timers, and the cause is identical.

JavaScript
for (var a = 0; a < 3; a++) setTimeout(() => console.log("var", a), 0);
for (let b = 0; b < 3; b++) setTimeout(() => console.log("let", b), 0);
Text
var 3
var 3
var 3
let 0
let 1
let 2

The timer callbacks run after the loops finish. With var, all three read the same variable, which is 3 by then. With let, each read its own.

Real use 1: private state

Before classes had private fields, a closure was the way to hide state, and it is still the lightest way.

JavaScript
function createBankAccount(initial) {
  let balance = initial;

  return {
    deposit(amount) {
      if (amount <= 0) throw new RangeError("amount must be positive");

      balance += amount;

      return balance;
    },
    withdraw(amount) {
      if (amount > balance) throw new RangeError("insufficient funds");

      balance -= amount;

      return balance;
    },
    get balance() {
      return balance;
    },
  };
}

const account = createBankAccount(100);

account.deposit(50);

console.log(account.balance);

try {
  account.balance = 1000;
} catch (error) {
  console.log(error.message);
}

console.log(account.balance);
Text
150
Cannot set property balance of #<Object> which has only a getter
150

The assignment account.balance = 1000 failed, since the property has a getter and no setter, and in a sloppy-mode script it would have been ignored without an error. The real balance did not change. There is no way to reach the balance variable from outside, and every change goes through methods that check the rules. A class with a #balance field gives the same protection with different syntax, and the section on closures versus classes compares the two.

Real use 2: function factories

A function that returns a function configured by its arguments is a factory. The returned function keeps the configuration in its closure.

JavaScript
function makeFormatter(currency, locale) {
  const format = new Intl.NumberFormat(locale, { style: "currency", currency });

  return (amount) => format.format(amount);
}

const usd = makeFormatter("USD", "en-US");
const gbp = makeFormatter("GBP", "en-GB");

console.log(usd(1234.5), gbp(1234.5));
Text
$1,234.50 £1,234.50

The expensive part, creating an Intl.NumberFormat, happens once per formatter, and the returned function reuses it. This pattern appears everywhere: logger factories that include a prefix, API clients that include a base URL and a token, validators that include limits and route handlers that include a service. A factory is a way of saying "do this, with these settings fixed".

Real use 3: callbacks that know their context

An event handler or a timer callback runs later, in a different place from where it was written, and the closure is how it still knows what it was for.

JavaScript
function attachLabel(items) {
  return items.map((item) => ({
    item,
    describe: () => `item ${item.id} is ${item.done ? "done" : "open"}`,
  }));
}

const tasks = attachLabel([
  { id: 1, done: true },
  { id: 2, done: false },
]);

console.log(tasks.map((task) => task.describe()));
Text
[ 'item 1 is done', 'item 2 is open' ]

Each describe closes over the item of its own pass. In browser code the same idea runs through every addEventListener call: the handler you pass uses the variables around it, long after the code that registered it has returned.

JavaScript
function onClickLogger(name) {
  return (event) => console.log(`${name} received ${event.type}`);
}

const target = new EventTarget();

target.addEventListener("ping", onClickLogger("first"));
target.addEventListener("ping", onClickLogger("second"));
target.dispatchEvent(new Event("ping"));
Text
first received ping
second received ping

Real use 4: memoization and caches

A closure can hold a cache that no other code can touch.

JavaScript
function memoize(fn) {
  const cache = new Map();

  return (key) => {
    if (cache.has(key)) return cache.get(key);

    const value = fn(key);

    cache.set(key, value);

    return value;
  };
}

let computations = 0;

const slowDouble = memoize((n) => {
  computations += 1;

  return n * 2;
});

console.log(slowDouble(4), slowDouble(4), slowDouble(5), computations);
Text
8 8 10 2

The cache map belongs to the closure, so each memoized function has its own, and callers cannot clear or corrupt it. Memoization is only correct for pure functions, and a cache with no limit can grow forever, so a long-running program needs an eviction rule such as a maximum size.

Real use 5: once, debounce and other wrappers

Wrappers that add behavior around a function are closures that hold the original function and a little state.

JavaScript
function once(fn) {
  let done = false;
  let result;

  return (...args) => {
    if (!done) {
      done = true;
      result = fn(...args);
    }

    return result;
  };
}

const setup = once(() => {
  console.log("setting up");

  return { ready: true };
});

console.log(setup(), setup() === setup());
Text
setting up
{ ready: true } true

once never exposes done or result, and the wrapper returns the same object on every call. Rate limiters, retry helpers, timing wrappers and logging decorators all follow this shape. The functions guide on this site has a debounce example built the same way, with the timer id held in the closure.

Real use 6: the module pattern

Before ES modules, a file's variables were global, and the standard way to avoid collisions was a function that ran immediately and returned an object with the public parts. The pattern is still meaningful, because it shows that a module is, in effect, a closure.

JavaScript
const analytics = (() => {
  const events = [];

  function track(name) {
    events.push({ name, order: events.length + 1 });
  }

  return {
    track,
    report: () => events.map((event) => `${event.order}:${event.name}`).join(" "),
  };
})();

analytics.track("open");
analytics.track("click");

console.log(analytics.report());
Text
1:open 2:click

An ES module gives you the same thing by default: top-level variables of a file are private to it, and only exported names are visible to others, with the module's scope kept alive by the exported functions that refer to it.

'''

Real use 7: partial application and configuration

A closure lets you fix some of a function's arguments now and supply the rest later.

JavaScript
function withPrefix(prefix) {
  return (message) => `[${prefix}] ${message}`;
}

const warn = withPrefix("warn");
const info = withPrefix("info");

console.log(warn("disk almost full"));
console.log(info("backup finished"));
Text
[warn] disk almost full
[info] backup finished

The same idea scales up to middleware, where a function takes a configuration and returns a handler, as in app.use(rateLimit({ max: 5 })). The options object is captured once, and the handler it returns runs on every request with those options in reach.

Stale closures

Because a closure holds a variable and not a snapshot, the common surprise is the opposite of the loop bug: a function that keeps reading an old value because the variable it captured was replaced, not changed.

JavaScript
function createState(initial) {
  let value = initial;

  return {
    get: () => value,
    set(next) {
      value = next;
    },
  };
}

const state = createState({ count: 1 });
const snapshot = state.get();

state.set({ count: 2 });

console.log(snapshot.count, state.get().count);
Text
1 2

snapshot holds the old object, and the new object replaced it inside the state. Anyone who took the object earlier sees the old one. This is the same behavior as any reference in JavaScript, and it is the core of the "stale closure" problem in React function components. A component function runs on every render, and each render creates new closures over that render's values of props and state. A callback created in one render keeps seeing that render's values, even after a later render has new ones.

JavaScript
function renderOnce(count) {
  return {
    logLater: () => console.log("count was", count),
  };
}

const first = renderOnce(1);
const second = renderOnce(2);

first.logLater();
second.logLater();
Text
count was 1
count was 2

Each "render" has its own count, and the callback from the first one never learns about the second. If an interval or an event listener is registered in the first render and never replaced, it keeps reporting 1. The fixes are to register a new callback when the values change, which is what a dependency array does in useEffect, to store the latest value in a mutable container such as a ref that the callback reads at call time, or to pass a function to the state setter, setCount((current) => current + 1), which receives the current value and does not depend on the captured one.

JavaScript
let latest = 0;

const intervalCallback = () => latest;

latest = 5;

console.log(intervalCallback());
Text
5

Reading through a mutable holder, here the outer variable latest, gives the current value every time. That is the idea behind a ref: a stable object that outlives renders, whose contents change.

Closures and asynchronous code

A closure is what lets an asynchronous callback use the variables of the code that scheduled it. In async functions, the same thing happens implicitly, since the code after an await is a continuation that closes over the function's variables.

JavaScript
async function loadAll(ids) {
  const results = [];

  for (const id of ids) {
    await new Promise((resolve) => setTimeout(resolve, 5));
    results.push(`item ${id}`);
  }

  return results;
}

console.log(await loadAll([1, 2, 3]));
Text
[ 'item 1', 'item 2', 'item 3' ]

The results array and the loop variable are in a scope that survives each pause. A related trap is shared mutable state between concurrent calls: two calls that run at the same time and read and change one outer variable can interleave their steps, and a closure makes it easy to share that variable without noticing.

JavaScript
let shared = 0;

async function bump() {
  const before = shared;

  await new Promise((resolve) => setTimeout(resolve, 5));

  shared = before + 1;
}

await Promise.all([bump(), bump()]);

console.log(shared);
Text
1

Both calls read 0, waited and wrote 1, so one increment was lost. Keep the read and the write together with no await between them, or keep the state in a place that serializes access.

Memory: what a closure keeps alive

A closure keeps the variables it uses reachable, and so everything those variables point to. Most of the time this is harmless. The problems come from closures that live longer than you expect and hold something large.

JavaScript
function attachHandler(registry) {
  const bigData = new Array(1_000_000).fill("x");

  registry.push(() => bigData.length);
}

function attachLightHandler(registry) {
  const bigData = new Array(1_000_000).fill("x");
  const size = bigData.length;

  registry.push(() => size);
}

const heavy = [];
const light = [];

attachHandler(heavy);
attachLightHandler(light);

console.log(heavy[0](), light[0]());
Text
1000000 1000000

The two handlers return the same number. The first one keeps the million-item array in memory for as long as the handler is registered, and the second copied the one number it needs, so the array can be collected when the function ends. The cost here is real memory, which we do not quantify, since it depends on the engine. The rule is general: a closure should capture what it needs, and copy small values out of large objects before creating long-lived callbacks.

Four situations account for most closure-related leaks. Event listeners that are never removed, since the target holds the listener and the listener holds its scope. Timers, setInterval in particular, that are never cleared. Caches in a closure with no size limit, such as an unbounded memoize. And callbacks stored in a long-lived registry, such as a list of subscribers that never unsubscribe. The cures are matching: remove listeners with removeEventListener or an AbortController signal, clear timers, bound the caches and return an unsubscribe function from every subscribe.

JavaScript
function subscribe(list, listener) {
  list.push(listener);

  return () => {
    const index = list.indexOf(listener);

    if (index !== -1) list.splice(index, 1);
  };
}

const listeners = [];
const unsubscribe = subscribe(listeners, () => console.log("event"));

console.log(listeners.length);

unsubscribe();

console.log(listeners.length);
Text
1
0

The returned function is a closure over list and listener, and calling it removes exactly the listener that was added. For caches keyed by objects, a WeakMap lets entries disappear when the key is collected, which avoids the unbounded growth.

Closures compared with classes and private fields

Both a closure and a class with a #private field can hold private state. They differ in cost, in tooling and in what they allow.

JavaScript
// closure version
function createLimiter(max) {
  let used = 0;

  return {
    take() {
      if (used >= max) return false;

      used += 1;

      return true;
    },
  };
}

// class version
class Limiter {
  #max;
  #used = 0;

  constructor(max) {
    this.#max = max;
  }

  take() {
    if (this.#used >= this.#max) return false;

    this.#used += 1;

    return true;
  }
}

const a = createLimiter(2);
const b = new Limiter(2);

console.log([a.take(), a.take(), a.take()], [b.take(), b.take(), b.take()]);
Text
[ true, true, false ] [ true, true, false ]

The behavior is identical. The closure creates new method functions for every object, since each take closes over its own variables. The class defines take once on the prototype, and instances share it, so a class is lighter when you create thousands of objects. The class also supports instanceof, inheritance and a recognizable type name in the debugger, and the closure version is shorter and does not involve this, which cannot be lost. For one or a few objects, such as a module-level service, a closure is fine. For many instances of one kind, use a class.

Closures and this

A closure captures variables, and this is not a variable in a regular function: it is set by the call. An arrow function treats this like a variable and captures it from the surrounding function, which is why an arrow closes over this and a regular function does not.

JavaScript
function plainCall(fn) {
  return fn();
}

const widget = {
  name: "widget",
  regular() {
    return plainCall(function () {
      return this === undefined ? "lost" : this.name;
    });
  },
  arrow() {
    return plainCall(() => this.name);
  },
};

console.log(widget.regular(), widget.arrow());
Text
lost widget

plainCall calls its argument with no owner, so the regular function's this is undefined, while the arrow closed over the this of the arrow method, which is widget. When in doubt, copy the value you need into a variable before creating the callback, or use an arrow.

Debugging closures

Every browser's developer tools show closures. In the debugger, paused inside a function, the scope panel lists Local, Closure and Global scopes, and the Closure entries are exactly the captured variables, named by the function that owns them. In Node.js, run with node --inspect and attach the Chrome DevTools to see the same panels. When a closure behaves strangely, check three things: which variable it captured, whether that variable has changed since, and whether two closures that you assumed were separate share one variable. A console.log inside the closure, printing the captured variable, answers the second question, and creating the closures in a separate function, so that each call gets its own scope, fixes most of the third.

Interview puzzles worth understanding

Closure questions in interviews reduce to the same two ideas: a closure captures variables, and each call to a function creates a new scope. Predict the output of each snippet before reading it.

JavaScript
function makeAdders() {
  const adders = [];

  for (let i = 1; i <= 3; i++) {
    adders.push((n) => n + i);
  }

  return adders;
}

const [addOne, addTwo, addThree] = makeAdders();

console.log(addOne(10), addTwo(10), addThree(10));
Text
11 12 13

Each pass of the let loop made a new i, so the three adders add 1, 2 and 3. With var, all three would add 4, since the shared i ends at 4.

JavaScript
function counterPair() {
  let count = 0;

  return [() => ++count, () => count];
}

const [increment, read] = counterPair();
const [otherIncrement, otherRead] = counterPair();

increment();
increment();
otherIncrement();

console.log(read(), otherRead());
Text
2 1

The functions of one pair share one count, and the second pair has its own. The question is the same as the one about private state, and the answer follows from "each call creates a new scope".

A closer look at the lexical environment

Tracing one example step by step makes the model concrete. Three nested functions each own a variable, and the innermost uses all of them.

JavaScript
function outer() {
  let x = 1;

  function middle() {
    let y = 10;

    function inner() {
      x += 1;
      y += 1;

      return x + y;
    }

    return inner;
  }

  return middle();
}

const f = outer();
const g = outer();

console.log(f(), f(), g());
Text
13 15 13

The first call to outer creates an environment with x as 1, and middle() creates one inside it with y as 10. inner is returned, and it holds a reference to the middle environment, which points to the outer one. Calling f() adds one to both variables, so x is 2 and y is 11 and the result is 13. The second call finds x at 2 and y at 11, so they become 3 and 12, and the result is 15. The call that built g created a second pair of environments, so g() starts from 1 and 10 and gives 13. The two chains are separate, and nothing links f and g.

Lexical means that the chain is fixed where the function is written, and not where it is called. A function does not see the variables of the code that calls it.

JavaScript
let value = "global";

function show() {
  return value;
}

function run() {
  let value = "local";

  return show();
}

console.log(run());
Text
global

show was written in the module scope, so it looks up value there, and the value inside run is invisible to it. A language with dynamic scope would print local. Some old shell languages work that way, and JavaScript does not, which is what makes closures predictable: you can answer any question about a variable by reading the nesting of the code.

Closures as hand-made iterators

Generators give you iterators with less code, and building one by hand shows what a closure is doing for them. The state, a position in the sequence, lives in a variable that next closes over.

JavaScript
function range(start, end) {
  let current = start;

  return {
    next() {
      return current < end
        ? { value: current++, done: false }
        : { value: undefined, done: true };
    },
    [Symbol.iterator]() {
      return this;
    },
  };
}

console.log([...range(1, 4)]);

const iterator = range(10, 12);

console.log(iterator.next(), iterator.next(), iterator.next());
Text
[ 1, 2, 3 ]
{ value: 10, done: false } { value: 11, done: false } { value: undefined, done: true }

Each call to range makes a new current, so two ranges can be consumed independently. The object is both an iterator, since it has next, and an iterable, since [Symbol.iterator] returns itself, so the spread syntax and for...of accept it. A generator function does the same bookkeeping for you, and keeps its local variables alive between yields in the same way: the paused generator is a closure whose scope survives the pause.

Other ways to keep data private

A closure is one of four ways to hide data in JavaScript, and it helps to know the others, since each has a different strength.

JavaScript
// 1. closure: not reachable at all
function makeSecret(value) {
  return { reveal: () => value.slice(0, 2) + "***" };
}

// 2. #private field: reachable only inside the class body
class PrivateToken {
  #value;

  constructor(value) {
    this.#value = value;
  }

  reveal() {
    return this.#value.slice(0, 2) + "***";
  }
}

// 3. WeakMap keyed by the instance
const store = new WeakMap();

class MappedToken {
  constructor(value) {
    store.set(this, value);
  }

  reveal() {
    return store.get(this).slice(0, 2) + "***";
  }
}

// 4. convention: an underscore prefix, not private at all
class ConventionToken {
  constructor(value) {
    this._value = value;
  }
}

console.log(makeSecret("abcdef").reveal());
console.log(new PrivateToken("abcdef").reveal());
console.log(new MappedToken("abcdef").reveal());
console.log(Object.keys(new ConventionToken("abcdef")));
Text
ab***
ab***
ab***
[ '_value' ]

The first three hide the value from the outside, and the fourth only asks politely. A closure is the oldest of the real ones and needs no special syntax. A #private field is enforced by the engine, is the clearest to read in a class and survives debugging tools that show closure scopes. A WeakMap predates #private and is still used to attach data to objects you do not own, such as DOM nodes, without keeping them alive. The conventions differ in whether the data can be reached through the debugger and through tools such as util.inspect, which a closure variable and a #private field both resist.

Gotchas catalog

Most closure bugs fall into a few families, and recognizing the family is half of the fix.

Mutation after capture. The closure sees changes to the object it captured, including ones made by other code.

JavaScript
const config = { retries: 1 };
const readRetries = () => config.retries;

config.retries = 5;

console.log(readRetries());
Text
5

If you want a frozen view, copy the value at creation, const retries = config.retries, or freeze the object.

Shadowing by accident. A parameter or inner variable with the same name hides the outer one, and the closure then captures the inner one.

JavaScript
const items = ["a", "b"];

function labelAll(items) {
  return items.map((item) => item.toUpperCase());
}

console.log(labelAll(["x"]), items);
Text
[ 'X' ] [ 'a', 'b' ]

Here the shadowing is deliberate, and the function uses its parameter. The bug appears when you meant to use the outer items and typed a parameter of the same name. ESLint's no-shadow rule reports it.

A shared variable between concurrent calls. Covered earlier: two async calls that read and write one captured variable can lose an update. Keep the read and the write adjacent, with no await between them.

A callback that outlives what it captured. A timer or listener that captures a component, a DOM node or a request object keeps it alive until it is cleared, which is the leak family covered above.

Expecting a snapshot. A function created in a loop with var sees only the final value. Use let, or create the function in a helper that takes the value as a parameter.

Testing code that uses closures

A closure's state is private, so test the behavior through the public functions, and not the variables. For a counter, call increment twice and assert that read returns 2. For a memoized function, count calls to the wrapped function with a spy and assert that repeated inputs call it once. For a factory, create two instances and assert that they do not share state, which is the property most likely to break by accident when someone moves a variable out of the factory into the module scope. And for timers, use fake timers, so that the test does not wait: the built-in Node.js test runner has mock.timers, and the closure that holds the pending callback behaves the same under the fake clock.

JavaScript
import { test } from "node:test";
import assert from "node:assert/strict";

function createLimiter(max) {
  let used = 0;

  return () => (used < max ? ++used <= max : false);
}

test("limiters do not share state", () => {
  const a = createLimiter(1);
  const b = createLimiter(1);

  assert.equal(a(), true);
  assert.equal(a(), false);
  assert.equal(b(), true);
});
Text
āœ” limiters do not share state (0.8ms)

The third assertion is the important one: it fails if used was declared outside createLimiter, which is the mistake that turns a factory into a singleton.

Closures in servers: request state and module state

On a server, the line between "one request" and "the whole process" decides where variables should live, and closures make it easy to draw that line in the wrong place. A variable declared at the top of a module is shared by every request that the process handles, since the module's scope stays alive for the life of the process. A variable declared inside the handler is created fresh per request, and a closure over it lives only as long as that request's callbacks do.

JavaScript
let lastUser = null;

function handleShared(user) {
  lastUser = user;

  return new Promise((resolve) => setTimeout(() => resolve("hello " + lastUser), 5));
}

function handleScoped(user) {
  const current = user;

  return new Promise((resolve) => setTimeout(() => resolve("hello " + current), 5));
}

const shared = await Promise.all([handleShared("ana"), handleShared("bo")]);
const scoped = await Promise.all([handleScoped("ana"), handleScoped("bo")]);

console.log(shared, scoped);
Text
[ 'hello bo', 'hello bo' ] [ 'hello ana', 'hello bo' ]

Two requests ran at the same time. In the shared version, both callbacks read lastUser after the second request had overwritten it, so the first caller received the second caller's data. That is the classic cross-request leak in a Node.js server, and it comes from a variable at the wrong level, not from anything exotic. In the scoped version, each request's callback closed over its own current. Keep per-request data in function parameters and locals, or in the framework's request object, and keep only configuration and caches in module variables.

Closures with currying and composition

Currying and composition are closures stacked on each other. A curried function returns a function for each argument, and each returned function closes over the arguments before it.

JavaScript
const curry = (fn) => {
  const curried = (...args) =>
    args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);

  return curried;
};

const volume = curry((w, h, d) => w * h * d);

console.log(volume(2)(3)(4), volume(2, 3)(4), volume(2)(3, 4));

const pipe = (...fns) => (input) => fns.reduce((value, fn) => fn(value), input);
const slugify = pipe(
  (text) => text.trim(),
  (text) => text.toLowerCase(),
  (text) => text.replace(/\s+/g, "-"),
);

console.log(slugify("  Hello Closure World "));
Text
24 24 24
hello-closure-world

curry collects arguments in the args of each closure until it has as many as the original function declares, then calls it. pipe closes over the list of functions and runs them in order. Neither needs a class or global state, and both are a few lines because functions can return functions that remember their inputs. The functional programming guide on this site builds on exactly this.

Closures in browser code

Browser APIs are full of callbacks, and each one is a closure. An event handler captures the elements and settings around it. A fetch chain captures the variables that the later steps need. A MutationObserver or IntersectionObserver callback captures whatever it must update.

JavaScript
function setupCounter(button, label) {
  let clicks = 0;

  button.addEventListener("click", () => {
    clicks += 1;
    label.textContent = `Clicked ${clicks} times`;
  });
}

The handler keeps clicks, button and label alive for as long as the button exists and the listener is attached, and no global variable is needed. When the button is removed from the page, the listener and the closure go with it, provided nothing else holds them. A listener on a long-lived target, such as window or document, that captures an element that is later removed keeps that element in memory, and the cure is to remove the listener when the component goes away, with removeEventListener or an AbortController signal passed in the options.

One sentence to remember

The whole guide compresses into a single idea, and it is worth saying slowly, because it carries most of the later detail.

If someone asks you to explain closures in a sentence, this one is accurate: a closure is a function that carries the variables of the place where it was written, and those variables keep their current values for as long as the function exists. Everything else in this guide is that sentence, applied to loops, state, callbacks, memory and design.

Recursion with a closure-held cache

A recursive function can carry its own cache in a closure, which turns an exponential algorithm into a linear one without changing its shape.

JavaScript
function makeFib() {
  const known = new Map([[0, 0], [1, 1]]);

  function fib(n) {
    if (known.has(n)) return known.get(n);

    const value = fib(n - 1) + fib(n - 2);

    known.set(n, value);

    return value;
  }

  return fib;
}

const fib = makeFib();

console.log(fib(10), fib(50));
Text
55 12586269025

The inner fib closes over known, so every recursive call shares one table, and a second call for the same n finds the answer at once. Without the cache, fib(50) would make billions of calls, and with it, about a hundred. The outer makeFib exists only to create the private table, and each call to it makes a separate, independent cache. This is memoization written by hand, and it shows that a closure and recursion combine well when the cache is the thing being closed over.

Closures and the event loop

A scheduled callback runs after the current call stack empties, but the scope it closes over was fixed at the time it was created. Combining the two facts explains the output of most timer puzzles.

JavaScript
function schedule() {
  let message = "created";

  setTimeout(() => console.log("timer sees", message), 0);

  message = "changed before the timer fired";

  console.log("sync sees", message);
}

schedule();
Text
sync sees changed before the timer fired
timer sees changed before the timer fired

The function finished first, in the same call, so message had its final value when the timer callback ran, and the callback read the variable and not the value that it had at scheduling time. If you need the value from the moment of scheduling, pass it as an argument to the callback or copy it into a const before the timer.

JavaScript
function scheduleSnapshot() {
  let message = "created";
  const snapshot = message;

  setTimeout(() => console.log("timer sees", snapshot), 0);

  message = "changed";
}

scheduleSnapshot();
Text
timer sees created

setTimeout also accepts extra arguments after the delay, setTimeout(fn, 0, message), which are passed to the callback and give the same snapshot without a separate variable.

Questions people ask about closures

Are closures only for functions that return functions? No. Any function that uses a variable from an enclosing scope is a closure over that variable, including a callback passed to map. The case of a returned function is just the one where the closure outlives its creator, which is where the effect is visible.

Do closures work with const? Yes. const prevents reassigning the variable, and a closure can still read it, and can change an object or array that it points to. A let variable can be reassigned by the closure.

Does every function create a closure that costs memory? Every function object carries a reference to its environment, and engines optimize the common case, so a function that uses no outer variables adds no meaningful cost. The memory matters when a long-lived function references something large, as in the earlier example.

Are closures related to higher-order functions? Closely. A higher-order function takes or returns functions, and when it returns one, that function is nearly always a closure over the arguments of the call that made it.

Can I see what a closure has captured from code? Not directly, which is the point of private state. Use the debugger's scope panel during development.

A practice plan

Reading about closures is not enough, since the understanding comes from predicting output and being wrong. Spend an hour on four exercises. First, write a counter factory and check that two counters do not share state. Second, write the loop bug on purpose with var, predict the output, run it and then fix it two ways. Third, write a memoize function and test it with a function that counts its own calls. Fourth, take a callback in code you maintain and list the variables it captures, then decide whether each one should be captured or passed in. After these, the scope panel in the debugger will show you what you already expect, and unfamiliar closure bugs will stop being mysterious. The most useful habit is the last exercise: when you write a callback, name the outer variables it uses, and ask whether they will have changed by the time it runs.

Rules we follow

Prefer let and const in loops, so that each pass has its own variable. Capture only what the closure needs, and copy small values out of large objects. Give every long-lived callback a way to be removed, and return an unsubscribe function from anything that registers one. Do not share a mutable variable between concurrent asynchronous calls without thinking about interleaving. Name closures that matter, since a named function shows up in stack traces and in the scope panel. And choose a class over a closure when you need many instances, inheritance or a visible type.

Where this guide stops

Closures are a general mechanism, and some topics need their own space. Generators and iterators keep state across calls in a similar way, with the language managing the scope, and the generators guide on this site covers them. Functional programming makes heavy use of closures for composition and currying, and its guide builds on this one. React hooks, useEffect dependency rules and the exact behavior of useCallback belong to a React guide. And engine-level details, such as which variables V8 puts in a shared context and when it can optimize a closure away, change between versions, so treat any statement about them with caution and measure when it matters.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.