Closures: a function keeps its variables

A closure is a function together with the scope it was created in. The function may be called long after that scope stopped running, and the names it read are still there, with the values they had reached. In JavaScript every function is a closure, because every function carries the environment of its birth; the word becomes useful when the function outlives the call that made it.

The previous lesson showed a callback remembering the loop binding it came from. This lesson takes the same mechanism apart: a returned inner function reads a parameter of the call that returned it, a counter keeps a variable alive between calls, and two functions made by one call share one binding. The next lesson builds the patterns that use it.

A function is born with its scope

makeGreeter returns the inner function greet, and greet reads the parameter greeting of the call that created it. Each call of makeGreeter makes a new environment with its own greeting, so the two functions built here answer differently.

function makeGreeter(greeting) { return function greet(name) { return `${greeting}, ${name}`; }; } const hello = makeGreeter('Hello'); const hi = makeGreeter('Hi'); console.log(hello('Ada')); console.log(hi('Grace'));

node born.mjs

Hello, Ada
Hi, Grace

The parameter of the first call is still readable in a call made much later, in a different part of the program. At the moment hello('Ada') runs, the call to makeGreeter has long returned and its stack frame is gone; the environment the function needed was moved to the heap and is kept for as long as a function refers to it.

The variables outlive the call

A variable declared inside the outer function and read by the inner one lives as long as the inner function does. The program below returns an object of two methods, and both close over the same count: increment writes it and value reads it.

function makeCounter() { let count = 0; return { increment() { count += 1; return count; }, value() { return count; }, }; } const counter = makeCounter(); console.log(counter.increment()); console.log(counter.increment()); console.log(counter.value()); const other = makeCounter(); console.log('other:', other.increment()); console.log('first again:', counter.value());

node survives.mjs

1
2
2
other: 1
first again: 2

The first counter reached 2 and stayed there while the second one started at 1, because the second call of makeCounter made a new count of its own. Nothing outside the two methods can write that variable: it has no name in the outer scope, so the only way to change it is a call to increment.

Two functions, one variable

A closure keeps the environment, not a copy of each value, and two functions created in the same call keep the same environment. The program below returns a reader and a writer for one value: the write through one function is visible through the other, while a second call of the factory gets a separate variable.

function makePair() { let value = 0; return { read: () => value, write: (next) => { value = next; }, }; } const pair = makePair(); pair.write(7); console.log('read:', pair.read()); const another = makePair(); console.log('other read:', another.read());

node shared.mjs

read: 7
other read: 0

The reader printed what the writer had stored, which is the whole of the shared state: one binding in one environment, reached by two functions. The second pair printed 0, because it is a different environment with its own value. Lesson 018 turns this pair into a counter and a module with private state.

What a closure keeps alive

An environment lives while a function refers to it, so a closure can hold a large object in memory long after the program stopped using it. The usual mistake is a small callback that reads one field of a large record: the whole record stays reachable and cannot be collected. The fix is to read the field into a local variable and close over that instead.

The other cost is the count. A loop that creates a function per pass creates an environment per pass, which is what makes the let loop of the previous lesson work and also what makes a million-element loop that pushes a closure a million small objects. Both costs are small next to what they buy, and both are worth knowing before a profile says the program holds more memory than its data explains.

Exercises

  1. Add a third greeter to born.mjs with a different greeting and print all three. How many environments does the program create?
  2. Change let count = 0; to count = 0; in survives.mjs and run it. What happens, and why does the missing keyword matter for the closure?
  3. Give the object of survives.mjs a reset method that sets count back to 0 and returns it. What does the next increment return?
  4. In shared.mjs, print pair.read itself. What is the value, and what does that say about where the variable lives?
  5. Write a function that returns a counter and a name, where the name is read once from a large object. Which variable does the counter close over?

Questions

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

  1. What is a closure?

    Answer

    A function together with the scope it was created in

    The function keeps its birth environment, and that pair is the closure.

  2. What does a variable of the outer function become for the inner function?

    Answer

    A live binding that survives the outer call

    The environment is kept, not copied, so later calls see the value the variable has reached.

  3. What does this program print? function makeAdder(n) { return (x) => x + n; } const add5 = makeAdder(5); console.log(add5(2));

    Answer

    7

    The returned function keeps the parameter n of the call, so 2 plus 5 is 7.

  4. What does this program print? function makeCounter() { let n = 0; return () => { n += 1; return n; }; } const a = makeCounter(); const b = makeCounter(); a(); console.log(a(), b());

    Answer

    2 1

    Each call of the factory makes its own n, so a reaches 2 while b starts from 0 and returns 1.

  5. What does this program print? let n = 1; function read() { return n; } n = 2; console.log(read());

    Answer

    2

    The function reads the binding when it is called, and by then the assignment has run.

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

    Answer

    1 2

    One environment serves both calls, so the counter increases from 1 to 2.

  7. Two functions returned by the same call of a factory close over...

    Answer

    the same environment, so they share its variables

    A closure keeps a reference to the environment, and both functions got the reference from the same call.

  8. Why can a closure keep a large object in memory?

    Answer

    Because the environment stays reachable while a function refers to it

    The captured environment is a live reference, so the values in it cannot be collected until the function is gone.

  9. What does the inner function of a counter see when it is called a second time?

    Answer

    The value the variable has now, changed by the first call

    The binding is live, so the second call reads the state the first call left behind.

  10. What does this program print? ``function makeGreeter(greeting) { return (name) => ${greeting}, ${name}; } const hello = makeGreeter("Hello"); console.log(hello("Ada"));``

    Answer

    Hello, Ada

    The parameter greeting is kept by the returned function, and name comes from the later call.

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