Closures power data privacy, memoization, and the module pattern. But they keep parent scopes alive in memory, so clean up when done.
Save
Complete lesson & earn 250 PX
EXERCISE
1Closures let you create truly private variables. No one outside the closure can read or modify them directly. This is JavaScript version of private fields.
Save
In many programming languages, you use the keyword "private" to hide data. does not have that for regular functions. Instead, you use closures.
A private counter:
function createCounter() {
var count = 0; // private, invisible from outside
return {
increment: function() { count++; return count; },
decrement: function() { count--; return count; },
getCount: function() { return count; }
};
}
var counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.decrement()); // 1
console.log(counter.getCount()); // 1
// There is NO WAY to access "count" directly
console.log(counter.count); // undefined
// The only way to interact with count is through the methods
Real-world example: a rate limiter:
function createRateLimiter(maxCalls, windowMs) {
var calls = 0;
var windowStart = Date.now();
return function(action) {
var now = Date.now();
if (now - windowStart > windowMs) {
calls = 0;
windowStart = now;
}
if (calls >= maxCalls) {
console.log("Rate limit exceeded. Try again later.");
return;
}
calls++;
action();
};
}
var limiter = createRateLimiter(3, 10000);
limiter(() => console.log("API call 1")); // works
limiter(() => console.log("API call 2")); // works
limiter(() => console.log("API call 3")); // works
limiter(() => console.log("API call 4")); // "Rate limit exceeded"
> Key Insight: Closures give you private state without using classes. The variables inside the outer function are completely hidden. Only the returned functions (the closure) can access them. This is the foundation of the Module Pattern.
Use closures for private variables (module pattern), results (memoization), and . Set closure references to null when no longer needed to free memory.