Closures in practice: counters and factories

A closure is easy to describe and easy to underuse. The four shapes below cover most of what a program needs from one: state that only a method can change, an object whose internals are hidden behind its methods, a function that builds a function with one value baked in, and a wrapper that runs its work exactly once. Every one of them is a few lines, and every one replaces a class or a global that would be larger.

All four are read from the same rule as the previous lesson: the inner function keeps the environment of the call, and that environment is reachable only through the functions the call returned. In JavaScript this is the usual way to keep a variable away from the rest of the program before the private class fields of the objects part.

A counter with private state

createCounter takes a starting value and returns three methods that share one count. The variable is not a property of the returned object, so counter.count is undefined and no line outside the methods can set it. reset uses the parameter of the call, which the methods also kept.

function createCounter(start = 0) { let count = start; return { increment() { count += 1; return count; }, decrement() { count -= 1; return count; }, reset() { count = start; return count; }, }; } const counter = createCounter(10); console.log(counter.increment()); console.log(counter.decrement()); console.log(counter.reset()); console.log('direct access:', counter.count);

node counter.mjs

11
10
10
direct access: undefined

Three calls and three answers, all from one variable that the caller cannot name. The last line is the point: the object has no count property, so the state cannot be read or written except through the three methods. Compare a plain object with a count property, where any line of the program may set it to a string.

Private state and the module pattern

An immediately invoked function expression, an IIFE, runs once and returns the object that is kept. Everything declared inside the function is invisible outside it, and the returned methods are the only doors. The program below hides a balance behind deposit, withdraw and a getter, and the getter appears in the keys of the object while the variable does not.

const bankAccount = (function () { let balance = 0; return { deposit(amount) { balance += amount; return balance; }, withdraw(amount) { if (amount > balance) { return 'insufficient funds'; } balance -= amount; return balance; }, get balance() { return balance; }, }; })(); console.log(bankAccount.deposit(100)); console.log(bankAccount.withdraw(30)); console.log(bankAccount.withdraw(500)); console.log('balance:', bankAccount.balance); console.log('keys:', Object.keys(bankAccount).join(', '));

node private.mjs

100
70
insufficient funds
balance: 70
keys: deposit, withdraw, balance

The second withdrawal was refused by a rule that lives inside the closure, and the balance stayed 70. The getter is a property of the object, so it shows up among the keys; the variable behind it is not there at all. A class with #balance does the same job with language syntax, and the objects part of the course comes back to the choice.

A function factory

A factory is a function whose product is another function. makeMultiplier bakes its argument into the returned arrow, so the new function needs one argument instead of two and reads like a verb. The same shape builds validators, formatters and column readers, wherever a parameter is fixed for a family of calls.

function makeMultiplier(factor) { return (value) => value * factor; } const double = makeMultiplier(2); const triple = makeMultiplier(3); console.log(double(5), triple(5));

node factory.mjs

10 15

Two functions from one line of code, each with its own factor. The factor of the first call is out of reach everywhere except inside double, which is why the function cannot be disturbed by a later change to the variable that was passed: numbers are copied when they are passed, as the lesson on references showed.

A wrapper that remembers

A closure can also remember whether something has happened. once takes a function and returns a version of it that runs on the first call and answers with the same result on every call after that. This is how an expensive setup is done at most once, and it needs no state outside the wrapper.

function once(fn) { let called = false; let result; return function (name) { if (!called) { called = true; result = fn(name); } return result; }; } const init = once((name) => `initialised for ${name}`); console.log(init('Ada')); console.log(init('Grace'));

node once.mjs

initialised for Ada
initialised for Ada

The second call passed a different name and got the first answer, because the work had already run. Two variables, called and result, carry the memory between calls, and neither can be reached from outside. A cache is the same idea with a Map in place of the single value, which the collections part builds.

Exercises

  1. Add a step parameter to createCounter and use it in increment and decrement. What does createCounter(10, 5) print after two increments?
  2. Print bankAccount.balance before the deposit in private.mjs. What is the value, and why is it not undefined?
  3. Make withdraw return a different message when the amount is exactly the balance. Which line of the output changes?
  4. Use makeMultiplier to build a function that converts minutes to seconds and print the result of one call.
  5. Change once so that it returns the arguments of the first call as well, in an object. Which part of the closure does the new property come from?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Why is counter.count undefined for the object createCounter returns?

    Answer

    Because count is a variable of the closure, not a property of the object

    The state lives in the environment the methods share, and the returned object only holds the methods.

  2. What does this program print? function create(start) { let n = start; return () => { n += 1; return n; }; } const c = create(10); console.log(c(), c());

    Answer

    11 12

    The first call moves n from 10 to 11 and the second from 11 to 12, both on the same binding.

  3. What does this program print? const counter = (() => { let n = 0; return { inc: () => (n += 1) }; })(); console.log(counter.inc(), counter.n);

    Answer

    1 undefined

    The method returns the new value of the hidden variable, and the object has no n property to read.

  4. What does an immediately invoked function expression give the module pattern?

    Answer

    A private scope that runs once and returns the public object

    The call runs at once, its inner names stay inside, and the returned object is the only door to them.

  5. What does this program print? function makeMultiplier(factor) { return (value) => value * factor; } const double = makeMultiplier(2); console.log(double(4));

    Answer

    8

    The returned function multiplied its argument by the factor of the call, so 4 times 2 is 8.

  6. What does this program print? function once(fn) { let done = false; let result; return (value) => { if (!done) { done = true; result = fn(value); } return result; }; } const init = once((value) => value * 10); console.log(init(2), init(5));

    Answer

    20 20

    The work ran on the first call only, so the second call returned the remembered result.

  7. Which variable of the once wrapper carries the answer between calls?

    Answer

    The local result, kept by the returned function

    result lives in the environment the returned function closes over, so every call can read the first result.

  8. What is a function factory?

    Answer

    A function that returns a new function with a value fixed inside it

    The factory call supplies the parameter and the returned function uses it on every later call.

  9. What does this program print? const account = (() => { let balance = 0; return { add: (amount) => { balance += amount; return balance; }, }; })(); account.add(5); console.log(account.balance);

    Answer

    undefined

    The balance is a closure variable and the returned object holds only the add method.

  10. What does the getter of the bank account object show in Object.keys?

    Answer

    It is listed, because a getter is a property of the object

    A getter defined in the object literal is an own property, so its name appears, while the variable behind it does not.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image