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
- When a function is created, it records a link to the variables of the scope around it.
- When it later runs, it looks up names it doesn’t define itself through that link.
- 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 rememberedfunction makeCounter() {
let count = 0;
return function nextValue() {
count += 1; // the inner function captured count
return count;
}; // count lives on after makeCounter returns
}
function makeMultiplier(factor) {
return (x) => x * factor; // factor is remembered
}func makeCounter() func() int {
count := 0
return func() int {
count++ // the inner function captured count
return count
} // count lives on after makeCounter returns
}
func makeMultiplier(factor int) func(int) int {
return func(x int) int { return x * factor } // factor is remembered
}// FnMut: calling it changes the state it captured.
fn make_counter() -> impl FnMut() -> u32 {
let mut count = 0;
move || {
count += 1; // `move` gave the closure its own count
count
}
}
fn make_multiplier(factor: i32) -> impl Fn(i32) -> i32 {
move |x| x * factor // factor is remembered
}- Python can read captured variables freely, but needs
nonlocalto assign to one. Without it,count += 1would create a new local. - JavaScript and Go capture variables by reference: the closure sees later changes to them.
- Rust makes you choose.
movegives the closure its own copy, and the return type says what calling it may do:Fnonly reads,FnMutcan change the captured state.
Where you’ve used them
- Callbacks and event handlers:
button.addEventListener('click', () => save(draftId))remembersdraftId. - Function factories:
make_multiplier(3)returns a function that triples. - Private state: the counter’s
countcan’t be reached except through the returned function. - Functional pipelines: a lambda passed to
filterthat refers to alimitvariable is a closure. See functional programming.
Common mistakes
- 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, uselet. - Forgetting
nonlocalin Python. Assigning to a captured variable without it raisesUnboundLocalError. - 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?
Each call to make_counter creates a new count, so b starts from 0 and returns 1.
Check yourself
Why doesn't count disappear when make_counter returns?
The inner function captured count. As long as the function is reachable, the variable is too.
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.
Finished this page?
Your list