Closures
Functions that remember.
Here's one of JavaScript's most powerful ideas. A function made inside another function remembers the variables around it, even after the outer function has finished. That memory is called a closure.

- A function inside a function
- It remembers its surroundings
- A closure
A counter
Make counter creates a count variable, and returns a little arrow function that adds one to it. Each time we call make counter, we get a brand new count. Run it. Counter A and counter B each remember their own count, and nothing else can touch it.
function makeCounter() {
let count = 0;
return () => {
count++;
return count;
};
}
const counterA = makeCounter();
const counterB = makeCounter();
console.log(counterA(), counterA(), counterA());
console.log(counterB());1 2 3 1
Where closures appear
Closures are everywhere in JavaScript, often without you noticing. Event handlers in web pages remember variables from where they were created. Timers do too. And closures are a neat way to keep data private, like the count, which nothing outside can change directly.
| key | value |
|---|---|
| Closure | a function plus its memory |
| Remembers | outer variables |
| Each call | a fresh memory |
| Used in | events, timers, privacy |
Summary
A closure is a function that remembers the variables from where it was made. Next, passing functions to other functions, with callbacks.
Key takeaways- Inner function remembers
- Private state
- Each call is separate