Understanding JavaScript Closures in Five Minutes
Closures sound academic, but you already use them every day. Here is the idea in plain words, with examples.
1 min read
A closure is a function that remembers the variables around it, even after the code that created those variables has finished running. That is the whole idea. The rest is just practice.
A tiny example
function makeCounter() {
let count = 0
return function () {
count += 1
return count
}
}
const next = makeCounter()
next() // 1
next() // 2makeCounter has finished, yet the inner function still reads and updates count. It closed over that variable.
Where you already use closures
- Event handlers that read values from the component that created them.
- Timers like
setTimeoutthat run later but still see earlier variables. - React hooks, where every render creates functions that close over that render's state.
The classic gotcha
Closures capture variables, not snapshots of values. In React this shows up as a stale value inside an effect or an interval. When a function seems to see an old value, it is usually holding on to a variable from an earlier render.
Why it matters
Once closures click, a whole category of bugs becomes easy to explain, and patterns like private state, memoisation and function factories stop feeling like magic.