Memoization with Closures
You'll learn how to use closures to cache expensive function results and avoid recalculating the same values.
What Is Memoization?
Memoization is an optimization technique where you store the results of function calls and return the cached result when the same inputs occur again. Instead of recalculating, you look up the answer.
Think of it like a chef who writes down recipes they've perfected. The first time they make a complex dish, they work out all the measurements. But once written down, they can instantly recall the recipe without redoing the work.
Using Closures to Cache Results
A closure lets a function remember its own private cache. The outer function creates a storage object, and the inner function checks this cache before doing any calculation:
function memoize(fn) {
const cache = {}; // Private storage via closure
return function(arg) {
if (arg in cache) {
console.log('Returning cached result');
return cache[arg];
}
console.log('Computing result');
const result = fn(arg);
cache[arg] = result;
return result;
};
}
function slowSquare(n) {
// Simulating expensive calculation
return n * n;
}
const memoizedSquare = memoize(slowSquare);
memoizedSquare(5); // Computing result → 25
memoizedSquare(5); // Returning cached result → 25
memoizedSquare(10); // Computing result → 100
The cache object persists between calls because of the closure. Each lookup avoids redundant work.
When to Memoize
Use memoization when:
- The same inputs happen repeatedly
- Calculations are expensive
- The function is pure (same input always produces same output)
Key Takeaway: Closures create private caches that remember previous function results, turning expensive calculations into instant lookups for repeated inputs.