Sub topic 3
Closures: Functions That Remember
This chapter assumes you can write arrow functions and that you know how block scope works with let and const. It also builds on the previous chapter's idea that functions are values you can return from other functions.
What a Closure Is
A closure is a function together with the variables it could see when it was created. When an inner function is returned from an outer one, it keeps those variables alive and can use them later, even after the outer function has finished running.
function makeCounter() {
let count = 0;
return () => {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next()); // 1
console.log(next()); // 2
const other = makeCounter();
console.log(other()); // 1 (separate closed-over state)Each call to makeCounter creates a new scope with its own count. The function stored in next holds a reference to one of those scopes, and other holds a reference to a different one. Nothing outside these functions can read or change count, so the variable is private.
Closures as Configuration
Functional code mostly uses closures to capture settings, not to hold changing state. The outer function takes the configuration, and the inner function does the work.
const makeGreeter = (greeting) => (name) => `${greeting}, ${name}!`;
const hello = makeGreeter('Hello');
const hola = makeGreeter('Hola');
console.log(hello('Ada')); // Hello, Ada!
console.log(hola('Grace')); // Hola, Grace!The greeting value is captured once and never changes. That makes hello a pure function: the same name always gives the same output. Later chapters on currying and partial application rely on this pattern.
Common Errors
Capturing a loop variable declared with var
Closures capture variables, not snapshots of their values. A var declaration creates a single variable for the whole function, so every closure created in the loop shares it.
const withVar = [];
for (var i = 0; i < 3; i++) withVar.push(() => i);
console.log(withVar.map((f) => f())); // [ 3, 3, 3 ]
const withLet = [];
for (let j = 0; j < 3; j++) withLet.push(() => j);
console.log(withLet.map((f) => f())); // [ 0, 1, 2 ]With let, each iteration gets a fresh binding, so each closure sees its own value.
Expecting a captured value to stay fixed
If the captured variable is reassigned later, the closure sees the new value. When you need a fixed value, capture a const or pass the value in as a parameter.
Holding memory longer than needed
As long as a closure is reachable, everything it captures stays in memory. If an event handler captures a large array, that array stays in memory until the handler is removed.
| Situation | Effect | Fix |
|---|---|---|
| `var` in a loop | All closures share one variable | Use `let` |
| Captured variable reassigned | Closure sees the latest value | Capture a `const` |
| Long-lived closure over large data | Memory is not freed | Capture only what you need |
Exercise
Write a function once(fn) that returns a new function. The new function calls fn the first time it is called and returns the result. On every later call, it returns that first result without calling fn again. Which variables does your closure capture?
Show answer
const once = (fn) => { let called = false; let result; return (...args) => { if (!called) { called = true; result = fn(...args); } return result; }; }; The returned function captures fn, called, and result. Each call to once creates its own copies of these, so separate wrapped functions do not share state.
Exercise
What does this code print? const fns = []; for (var k = 0; k < 2; k++) { const v = k; fns.push(() => v); } console.log(fns.map((f) => f()));
Show answer
It prints [ 0, 1 ]. Even though k is declared with var, each closure captures v, a block-scoped const that gets a new binding on every iteration.