Memoization

Difficulty: Intermediate

Question

What is memoization in JavaScript? How do you implement a generic memoize function, and when should (and should not) you use it?

Answer

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.

How a memoize wrapper works

  1. Build a cache key from the arguments.
  2. If the cache has that key, return the stored value (a cache hit).
  3. Otherwise call the original function, store the result under the key, and return it (a cache miss).

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.

Where it pays off

When memoization hurts

Memoization vs general caching

AspectMemoizationApplication cache (Redis, CDN)
ScopeOne function, in process memoryShared across processes or servers
KeyFunction argumentsAny key you design
InvalidationUsually none, or LRU/TTLExplicit TTLs and eviction policies
LifetimeUntil the process or closure diesSurvives restarts and deploys
A memoize cache living in a closure. Repeat inputs under Tweak and watch cache hits skip the slow function.
  1. memoize runs once: Its scope holds the original function and an empty Map cache.
  2. The returned function closes over the cache: Only fastSquare can reach the cache.
  3. Cache miss: The original function runs and the result is stored under its input.
  4. Cache hit: A repeated input returns the stored value without recomputing.

Code examples

Generic memoize and memoized Fibonacci

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.

Bounded LRU memo and promise deduplication

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.

Key points

Common follow-up questions

Interview tips

Concepts covered

Memoization, Cache Key, Pure Functions, LRU Cache, Promise Caching

More JavaScript Interview questions