Member-only story
JavaScript Closures Explained — Build Private Variables, Function Factories, and Stateful Functions
JavaScript Mastery Series Part 35
Zayd Islam
8 min read14 hours ago
Read Part 34
Press enter or click to view image in full size
Discover how JavaScript functions remember variables from their surrounding scope, even after the outer function has finished executing.
Have you ever wondered how a function can access a variable that should no longer exist?
Consider this example:
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
Something interesting is happening here.
The createCounter() function has already finished executing, yet the returned function can still access and update count .
How?
The answer is closures.
Closures are one of JavaScript’s most powerful features.…