Closure is the ability of a function to remember the variables that are declared in its outer scope.
Use cases:
1. Data Encapsulation
Closures let you create private state. In many object-oriented languages, you have keywords like private or protected. JavaScript doesn’t natively offer these access modifiers, but closures provide a pattern to emulate them.
Example:
function createCounter() {
let count = 0; // Private variable
return {
increment: function() {
count++;
console.log('Count:', count);
},
getCount: function() {
return count;
}
};
}
const counter = createCounter();
counter.increment(); // Output: Count: 1
counter.increment(); // Output: Count: 2
console.log('Current Count:', counter.getCount()); // Output: Current Count: 2
2. Factory Functions
They allow you to create function factories that generate specialized functions. For instance, you might have a function that sets up some local variables and returns an inner function that uses those variables in specialised ways.
Example:
function createMultiplier(multiplier) {
return function(number) {
return number * multiplier;
};
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log('Double of 5:', double(5)); // Output: Double of 5: 10
console.log('Triple of 5:', triple(5)); // Output: Triple of 5: 15
3. Currying and Partial Application
Closures enable the creation of new functions from existing functions with some arguments pre-filled.
Example:
function add(a) {
return function(b) {
return a + b;
};
}
const addFive = add(5);
console.log('5 + 10 =', addFive(10)); // Output: 5 + 10 = 15
console.log('5 + 20 =', addFive(20)); // Output: 5 + 20 = 25
4. Memoization
By storing computed results in the closure, you can optimise expensive function calls.
Example:
function memoizedFibonacci() {
const cache = {}; // Closure to store computed values
function fib(n) {
if (n in cache) {
return cache[n];
}
if (n < 2) {
return n;
}
const result = fib(n - 1) + fib(n - 2);
cache[n] = result;
return result;
}
return fib;
}
const fib = memoizedFibonacci();
console.log('Fibonacci of 10:', fib(10)); // Output: Fibonacci of 10: 55
For detailed explanation: