Difficulty: Intermediate
What is memoization in JavaScript? How do you implement a generic memoize function, and when should (and should not) you use it?
Memoization is an optimisation where a function stores the result for each set of inputs it has already seen and returns the cached result on repeat calls instead of recomputing it. It trades memory for speed, and it is only safe for pure functions, whose output depends solely on their arguments and which have no side effects. In JavaScript a memoizer is usually a higher-order function that wraps the original function with a closure holding a Map cache.
The closure keeps the cache private to that wrapped function. For a single primitive argument the argument itself is the key. For several arguments, a common approach is JSON.stringify(args), which works for plain data but is slow for large objects, ignores undefined inside objects, and treats {a:1,b:2} and {b:2,a:1} as different keys. For object arguments where identity matters, a WeakMap keyed on the object avoids both the serialisation cost and memory leaks.
Intl.NumberFormat('en-IN') instances are worth caching), derived data in a UI.useMemo, useCallback and React.memo, and selector libraries like Reselect, are memoization tools. React Compiler (stable in 2025) now inserts much of this automatically.getCurrentPrice() or anything reading Date.now() or a database returns stale data.| Aspect | Memoization | Application cache (Redis, CDN) |
|---|---|---|
| Scope | One function, in process memory | Shared across processes or servers |
| Key | Function arguments | Any key you design |
| Invalidation | Usually none, or LRU/TTL | Explicit TTLs and eviction policies |
| Lifetime | Until the process or closure dies | Survives restarts and deploys |
function memoize(fn, keyFn = (...args) => JSON.stringify(args)) {
const cache = new Map();
return function (...args) {
const key = keyFn(...args);
if (cache.has(key)) return cache.get(key);
const result = fn.apply(this, args);
cache.set(key, result);
return result;
};
}
let calls = 0;
const fib = memoize(n => {
calls++;
return n < 2 ? n : fib(n - 1) + fib(n - 2); // recursive calls hit the memo
}, n => n);
console.log(fib(50));
console.log('function bodies executed:', calls);
console.log(fib(50), 'calls still', calls);
Because the recursion calls the memoized fib, each n from 0 to 50 is computed exactly once. Without memoization fib(50) would need billions of calls.
function memoizeLRU(fn, max = 100) {
const cache = new Map(); // Map keeps insertion order
return key => {
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key);
cache.set(key, value); // mark as most recently used
return value;
}
const value = fn(key);
cache.set(key, value);
if (cache.size > max) cache.delete(cache.keys().next().value); // evict oldest
return value;
};
}
let requests = 0;
const fetchProfile = id =>
new Promise(resolve => { requests++; setTimeout(() => resolve({ id }), 10); });
const getProfile = memoizeLRU(id => {
const p = fetchProfile(id);
p.catch(() => {}); // a real version would also evict the key on rejection
return p;
}, 2);
await Promise.all([getProfile('u1'), getProfile('u1'), getProfile('u1')]);
console.log('network requests:', requests);
Caching the promise means concurrent callers share one in-flight request. Using Map insertion order gives a simple LRU that caps memory use.
Memoization, Cache Key, Pure Functions, LRU Cache, Promise Caching