A Closer Look at Functions
Closures
A function keeps access to the variables it was born in, even after that scope returns.
Loading visual…
Definition
A closure is a function together with references to the variables from the scope where it was created. When a function is returned from or passed out of its parent, it carries that surrounding state with it, so it can still read and update those variables long after the parent has finished running.
Examples
function makeCounter() {
let count = 0;
return () => ++count;
}
const next = makeCounter();
next(); // 1
next(); // 2The returned arrow function keeps a live reference to count, so each call updates the same private variable.
Where you see this
- Private state in a module or hook (a value only the returned functions can touch).
- Event handlers and callbacks that remember the data they were set up with.
- Function factories like debounce, throttle, once, and memoize.