Member-only story
JavaScript closures allow inner functions to access variables in outer functions even after the outer functions have returned. This enables powerful programming patterns but also seems confusing at first.
In this article, we go beyond closure theory and look at 3 totally practical examples of common problems that closures can elegantly solve in JavaScript. Understanding these practical use cases helps unlock the true power of closures.
But first, a quick refresher on closures!
Closures in a Nutshell
In JavaScript, functions can be nested within other functions. Inner functions implicitly form closures — they “close in” on variables from outer function scopes even after execution:
function outer() {
let counter = 0;
function inner() {
counter++;
console.log(`Counter is ${counter}`);
}
return inner;
}
let myFunc = outer();
myFunc(); // Counter is 1
myFunc(); // Counter is 2
myFunc(); // Counter is 3
Here, counter persists via the closure after outer exits because inner closes in on it.