programmingconcepts

§ 4.3 · Paradigms

Closures

A function that remembers the variables around where it was created, even after that code has finished running.

A closure is a function bundled with the variables from the scope where it was created. When an outer function returns an inner function, the inner one keeps access to the outer one's local variables, even though the outer call has finished. Closures power callbacks, event handlers, function factories and private state without classes.

A closure is
A function plus captured variables
Captured variables
Outlive the call that made them
Used for
Callbacks, factories, private state
Python needs
nonlocal to reassign a captured variable
Requires
FunctionsFunctional programming

The puzzle

Normally a function’s local variables disappear when it returns; they lived in its frame on the call stack. So how can this work?

function makeCounter() {
  let count = 0;
  return () => ++count;
}
const next = makeCounter();  // makeCounter has finished...
next(); // 1
next(); // 2               ...but count is still alive

The inner function uses count, so the language keeps count alive, on the heap, for as long as the inner function exists. The function plus the variables it captured is a closure.

How it works

  1. When a function is created, it records a link to the variables of the scope around it.
  2. When it later runs, it looks up names it doesn’t define itself through that link.
  3. As long as the function is reachable, so are the captured variables. When nothing refers to the function any more, the garbage collector frees both.

Each call to the outer function creates a fresh set of variables, so each closure gets its own.

def make_counter():
    count = 0

    def next_value():
        nonlocal count  # use the captured variable, not a new local one
        count += 1
        return count

    return next_value  # count lives on after make_counter returns


def make_multiplier(factor):
    return lambda x: x * factor  # factor is remembered
  • Python can read captured variables freely, but needs nonlocal to assign to one. Without it, count += 1 would create a new local.
  • JavaScript and Go capture variables by reference: the closure sees later changes to them.
  • Rust makes you choose. move gives the closure its own copy, and the return type says what calling it may do: Fn only reads, FnMut can change the captured state.

Where you’ve used them

  • Callbacks and event handlers: button.addEventListener('click', () => save(draftId)) remembers draftId.
  • Function factories: make_multiplier(3) returns a function that triples.
  • Private state: the counter’s count can’t be reached except through the returned function.
  • Functional pipelines: a lambda passed to filter that refers to a limit variable is a closure. See functional programming.

Common mistakes

  1. Closures in a loop. In old JavaScript with var, or in Python, every closure made in a loop captures the same loop variable, so they all see its final value. In Python, bind it as a default argument: lambda x, i=i: x * i. In JavaScript, use let.
  2. Forgetting nonlocal in Python. Assigning to a captured variable without it raises UnboundLocalError.
  3. Accidental memory leaks. A long-lived closure keeps everything it captured alive. An event handler that captures a large object keeps it in memory until the handler is removed.

Check yourself

Check yourself

a = make_counter() is called 3 times. Then b = make_counter() is called once. What does b() return?

Check yourself

Why doesn't count disappear when make_counter returns?

Sources

  • Harold Abelson and Gerald Jay Sussman, Structure and Interpretation of Computer Programs, 2nd edition (1996), section 3.2, “The Environment Model of Evaluation.”
  • MDN Web Docs, “Closures,” developer.mozilla.org.
  • The Rust Programming Language, chapter 13, “Closures: Anonymous Functions that Capture Their Environment,” doc.rust-lang.org/book.

Newsletter

One new concept each week, by email.

Signup opens soon.