JavaScript Closures: Finally Making Sense of Them
Closures are one of the most powerful concepts in JavaScript. Let me break them down with clear examples.
What Is a Closure?
A closure is a function that remembers the variables from its outer scope, even after the outer function has finished running.
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
The inner function "closes over" the count variable. Even though createCounter has returned, the inner function still has access to count.
Why It Matters
Closures are everywhere in JavaScript: event handlers, callbacks, React hooks, module patterns, and more. Understanding them deeply will make you a significantly better developer.
Practical Example: Private State
function createUser(name) {
let loginCount = 0;
return {
getName: () => name,
login: () => {
loginCount++;
return ${name} logged in (${loginCount} times);
},
};
}
const user = createUser('Alice');
console.log(user.login()); // "Alice logged in (1 times)"
console.log(user.login()); // "Alice logged in (2 times)"
The loginCount variable is completely private — no external code can access it directly.