JavaScript Closures in Production: When to Use Them and When to Use a Class

9 min read0 views

What a closure is, how p-limit and Zustand use closures for private state, why quick-lru is a class instead, and how to choose between the two in production code.

Languages and Frameworks

I haven't written closures in production code. I know the definition, but tutorials tend to use counters and makeAdder, and those don't show when a closure is the right tool in a real codebase. So I read how three public libraries handle it: p-limit, Zustand and quick-lru. The first two use closures. The third is a class, which gives a useful contrast.

This post is for developers who can already say what a closure is and want to see one doing a job. It covers the definition, two production examples, one class-based example, how to choose between them, and a memory gotcha.

The code below comes from each repo's main branch in November 2026, trimmed for length. These repos change, so check the source before relying on a detail.

What a closure is

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

Closure Diagram

function createCounter() {
  let count = 0;
  return () => ++count;
}

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

const b = createCounter();
b(); // 1

createCounter has already returned when you call a, but count is still alive because the returned function refers to it. Nothing outside can read or change count except through that function. And b starts from 1, because every call to createCounter creates its own count.

Two properties matter for production code: the state is private, and every call makes an independent instance. The examples below use both.

Example 1: p-limit

p-limit runs async tasks with a cap on how many run at the same time. If you have 500 URLs to fetch and want at most 5 requests in flight, you write this:

const limit = pLimit(5);
const results = await Promise.all(urls.map((url) => limit(() => fetch(url))));

Here is the shape of the source, with validation and some internals removed:

export default function pLimit(concurrency) {
  const queue = new Queue();
  let activeCount = 0;

  const resumeNext = () => {
    if (activeCount < concurrency && queue.size > 0) {
      activeCount++;
      queue.dequeue().run();
    }
  };

  const next = () => {
    activeCount--;
    resumeNext();
  };

  // run() and enqueue() are omitted here

  const generator = (function_, ...arguments_) =>
    new Promise((resolve, reject) => {
      enqueue(function_, resolve, reject, arguments_);
    });

  Object.defineProperties(generator, {
    activeCount: { get: () => activeCount },
    pendingCount: { get: () => queue.size },
    // clearQueue, concurrency and map are omitted here
  });

  return generator;
}

queue, activeCount and concurrency are plain variables inside pLimit. Every inner function (resumeNext, next, the returned generator) closes over them. Callers never get a reference to the queue. They get a function to call, plus activeCount and pendingCount as getters, so they can read the numbers but can't set them.

Each pLimit() call creates its own queue and counter, so two limiters don't interfere with each other. One limiter per external API, each with its own limit, works without any extra code.

limitFunction in the same file wraps a function with a limiter, and the wrapper works because it closes over the limit it created:

export function limitFunction(function_, options) {
  const limit = pLimit(options);

  const limitedFunction = (...arguments_) =>
    limit(() => function_(...arguments_));
  // ...
  return limitedFunction;
}

A closure fits here because the job is one behavior with two pieces of hidden state, and callers only need to call a function. A class would work too, but you'd write new Limiter(5).run(fn) and have to decide what to do about this.

Example 2: Zustand's vanilla store

Zustand is a state management library. Underneath its React bindings there is a framework-free store in src/vanilla.ts. I removed the TypeScript types and getInitialState to keep this short:

const createStoreImpl = (createState) => {
  let state;
  const listeners = new Set();

  const setState = (partial, replace) => {
    const nextState = typeof partial === "function" ? partial(state) : partial;
    if (!Object.is(nextState, state)) {
      const previousState = state;
      state =
        replace ?? (typeof nextState !== "object" || nextState === null)
          ? nextState
          : Object.assign({}, state, nextState);
      listeners.forEach((listener) => listener(state, previousState));
    }
  };

  const getState = () => state;

  const subscribe = (listener) => {
    listeners.add(listener);
    // Unsubscribe
    return () => listeners.delete(listener);
  };

  const api = { setState, getState, subscribe };
  state = createState(setState, getState, api);
  return api;
};

In this trimmed version, state and listeners can only be reached through three functions, and that is the whole public surface of a store.

Two details in this code are worth a closer look. subscribe returns a function that closes over listener, and that function is the unsubscribe. The caller doesn't need an ID or a token to clean up, because the cleanup function already knows what to remove. And none of these functions use this, so const { getState } = store is safe. With a class, a method pulled off the instance and passed around as a callback loses its this unless you bind it.

setState also replaces the state object instead of mutating it (Object.assign({}, state, nextState)), so listeners receive the previous and the new state as two separate objects they can compare. The Object.is check skips the update, and the listeners, when the new value is the same as the current one.

Example 3: quick-lru is a class

quick-lru is a small cache that evicts old entries when it reaches a size limit. It's a class:

export default class QuickLRU extends Map {
  #size = 0;
  #cache = new Map();
  #oldCache = new Map();
  #maxSize;
  #maxAge;
  #onEviction;

  constructor(options = {}) {
    super();

    if (!(options.maxSize && options.maxSize > 0)) {
      throw new TypeError("`maxSize` must be a number greater than 0");
    }

    this.#maxSize = options.maxSize;
    // ...
  }

  get(key) {
    /* ... */
  }
  set(key, value, { maxAge = this.#maxAge } = {}) {
    /* ... */
  }
  has(key) {
    /* ... */
  }
  peek(key) {
    /* ... */
  }
  delete(key) {
    /* ... */
  }
  clear() {
    /* ... */
  }
  // and more
}

I can see three reasons this works as a class:

  • It extends Map, so a QuickLRU is a Map and can be passed to code that expects one. A closure returning a plain object can't do that.
  • It has a full set of methods (get, set, has, peek, expiresIn, delete, clear and others) that all work on the same internal state. In a class, those methods live once on the prototype and every instance shares them.
  • The # fields are private to the class, which gives it the same hiding p-limit gets from a closure.

The last point matters for the choice. Before #private fields arrived in ES2022, a closure was the usual way to hide state in JavaScript. Classes can do it now, so privacy alone doesn't decide between the two.

Closure or class

Here is how I'd compare them after reading these three:

Closure (factory function)Class
Private stateVariables in the outer function#private fields
How you create oneCall the functionnew
instanceof, extendsNot availableAvailable
MethodsNew function objects on every callShared on the prototype
thisNot neededMethods lose it when passed around unbound
Seen in this postp-limit, Zustandquick-lru

A closure is a good fit when:

  • The thing does one job, or a small set of related jobs, around a little hidden state.
  • Callers should treat it as a function or a small object of functions.
  • You want to pass its methods around as callbacks without binding.
  • You don't need instanceof or inheritance.

A class is a good fit when:

  • The thing is an entity with many methods working on shared state.
  • You need extends, instanceof, or to stand in for a built-in like Map.
  • You create a very large number of instances. A closure allocates its inner functions on each call, while a class shares its methods on the prototype. For a handful of instances this doesn't matter. For many thousands, it can.
  • Your team or framework already expects classes, for example in dependency injection.

Neither list is a rule.

A memory gotcha

A closure keeps what it references alive for as long as the closure itself can be reached. When something long-lived holds the closure, like an event listener or a list of subscribers, everything the closure references stays in memory too, even if nothing else uses it.

Here is the shape of it with the Zustand store from earlier:

const report = loadLargeReport();
const unsubscribe = store.subscribe((state) => draw(report, state));

The store keeps the listener in its listeners set, and the listener closes over report. While the listener is in that set, report can't be freed. Calling unsubscribe() removes the listener from the set, so the store no longer holds the closure and the memory can be reclaimed. Drop your own reference to unsubscribe after calling it, too, because that function closes over the listener as well.

This is why subscribe in Zustand returns an unsubscribe function. The closure lives as long as something references it, so the store needs a way to be told to let go. If you build your own closure-based API that registers callbacks, such as listeners, timers or cache entries, return a function that removes them.

How to start

Pick one small piece of your own code that keeps module-level state, like a cache, a counter or a debounce timer, and try these steps:

  1. Rewrite it as a factory function that creates the state inside and returns the functions that use it.
  2. Create two instances and check that they don't share state. Closures give you this for free, and module-level variables don't.
  3. Write a class version of the same thing and compare how callers use each one.
  4. Read the source of p-limit in full. It's about 150 lines, and the core is what this post covered.

If you've written a closure for production code, I'd like to hear what it was, and whether you'd write it the same way now.

Cheers!

Stay Updated

Get notified when I publish new ideas about technology, system design, and human-centered engineering.