पाठ 8 / 25
Closures
Functions that remember their surroundings.
Capturing variables from an outer scope
A closure is a function together with the variables from the scope where it was created. In JavaScript every function closes over the variables it references, so an inner function returned from an outer one can still read them after the outer function has finished. Closures power function factories, partial application, private state and callbacks. In FP style, prefer closures over constants; closing over mutable variables reintroduces hidden state and is a classic source of bugs (for example var in loops).
Factories and private state
Captured values outlive the outer call.
// Closure over a constant: a function factory
const multiplier = (factor: number) => (x: number) => x * factor;
const double = multiplier(2);
const triple = multiplier(3);
// double(5) evaluates to 10, triple(5) to 15
// Closure over mutable state: encapsulated, but no longer pure
function makeCounter() {
let count = 0;
return () => ++count; // each call returns a different value
}
const next = makeCounter();
next(); // 1
next(); // 2Closures can hold memory
A closure keeps its captured variables alive. A long-lived callback that captures a large object prevents that object from being garbage-collected.
त्वरित जाँच: Why is `makeCounter()`'s returned function not pure?
- It has no parameters
- Closures are always impure
- It reads and updates captured mutable state, so repeated calls give different results
- It is defined inside another function
Answer
It reads and updates captured mutable state, so repeated calls give different results — Closing over constants keeps purity; closing over mutable state does not.