Functions
Closure
A function plus the variables around the place it was created.
Why it exists
Sometimes a function needs memory between calls: a counter, a cache, an "already done" flag. A global variable is a bad fit — any code can spoil it, and there's only one for everyone. A closure gives the function private memory: the variable is reachable only by that function and lives as long as it does. React hooks, event handlers, debounce and modules with private state are all built on it.
Where it's used
- State in React:
useState,useEffectand handlers "see" the props and state of their render. - Function wrappers:
once,memoize,debounce,throttle. - Function factories:
makeMultiplier(2),createLogger("api"). - Callbacks and handlers that need data from their surroundings:
items.map((item) => item.price * rate).
Syntax
function outer() {
let memory = 0;
return function inner() {
memory += 1; // sees the outer function's variable
return memory;
};
}Examples
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next();
next(); // → 2function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a();
a();
b(); // → 1let rate = 1.1;
const toUsd = (eur) => eur * rate;
rate = 1.5;
toUsd(2); // → 3function greeter(greeting) {
return (name) => `${greeting}, ${name}!`;
}
greeter("Hello")("Byte"); // → "Hello, Byte!"Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
Every function call creates its own environment — the set of its local variables. A function created inside gets a reference to that environment and can read and change its variables.
Normally a function's variables disappear when it finishes. But if an inner function was returned (or passed on as a callback), the environment stays alive: a living function refers to it.
Crucially, the function remembers the variable itself, not its value at creation time: if the variable changes later, the function sees the new value.
Each call of the outer function creates a new environment. That's why two counters from makeCounter() are independent — each has its own count.
Traps
How it differs from…
- Scope
Scope decides which variables a function can see; a closure is the fact that it keeps seeing them after the outer function has returned.
- Functions as values
Closures are possible because functions are ordinary values: they can be returned and passed on together with their environment.
When to pick something else
If state has to be visible and changeable from different places (a cart, user settings), hiding it in a closure is awkward — an object, a class or a state store is better. A closure is good for a small private memory of a single function.