r/learnjavascript • u/Intelligent-Try-4958 • 4h ago
Closures explained as a backpack, with one short example
Closures are one of those topics that shows up in every interview and every tutorial, and most explanations jump straight to "lexical environment". Here's a simpler way to think about them.
A closure is a function plus the variables it could see when it was created. Think of it as a backpack the inner function carries around.
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a(); // 1
a(); // 2
b(); // 1 <- b has its own backpack
makeCounter has already returned by the time you call a(), so normally count would be gone. But the arrow function still needs it, so JavaScript keeps it alive. Every call to makeCounter packs a fresh backpack, which is why b starts again at 1.
Where you'll actually use this:
- Private state: nothing outside
makeCountercan touchcount. - Function factories:
makeDiscount(10)returns a function that always takes 10% off. - Run once: a
once(fn)wrapper that remembers whether it has run. - Loops: closures capture variables, not values, which is why
letin aforloop behaves andvardoesn't.
Try it: write makeCounter(start) so it can begin from any number. (Answer: let count = start and default start = 0.)
The full lesson, with a diagram, more examples and a practice exercise (free site I made, no sign-up): https://looplooplearn.com/courses/javascript-essentials/closures/?utm_source=reddit
Happy to answer questions about closures here either way.
1
u/senocular 3m ago
I was never a big fan of the backpack metaphor because it never seemed to work very well with multiple closures in the same scope. A slight modification gives us:
Does inc and dec have their own backpacks? Or are they wearing the same backpack since count is shared? And if so, do they get separate shoulder straps or do they each have to use the same straps?