Closures
10 min read
What Is a Closure?
A closure is a function that remembers the variables from its surrounding scope even after that scope has finished executing. Every function in JavaScript forms a closure over its lexical environment.
javascript
function makeCounter(start = 0) {
let count = start;
return {
increment() { count++; },
decrement() { count--; },
value() { return count; }
};
}
const counter = makeCounter(10);
counter.increment();
counter.increment();
counter.decrement();
console.log(counter.value()); // 11
// `count` is private — not accessible from outsideClosures enable data privacy, factory functions, memoization, and partial application. They are one of JavaScript's most powerful — and most misunderstood — features.
Practical Example: Memoization
javascript
function memoize(fn) {
const cache = new Map();
return function(...args) {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
const slowSquare = (n) => {
// imagine expensive computation
return n * n;
};
const fastSquare = memoize(slowSquare);
fastSquare(42); // computed
fastSquare(42); // returned from cacheClosures hold references to outer variables, preventing garbage collection. In long-running apps, storing large objects in a closure that outlives its use can cause memory leaks. Nullify unneeded references when you are done with them.
Ready to test yourself?
Practice JavaScript— quiz & coding exercises