Memoization

Caching a pure function's results, keyed by its arguments, so a repeated call with the same input returns instantly instead of recomputing.

Purpose

Memoization wraps a function so repeated calls with the same arguments return a cached result instead of recomputing it. It only produces correct results for a pure function β€” recall Pure function β€” since the cache assumes the same input always maps to the same output.

Example

function memoize(fn) {
  const cache = new Map(); // held in the closure, private to this memoized function
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}

function slowSquare(n) {
  console.log('computing...');
  return n * n;
}

const fastSquare = memoize(slowSquare);
fastSquare(5); // logs "computing...", returns 25
fastSquare(5); // no log β€” returns the cached 25 directly

Behavior notes

  • The cache lives in a closure, private to that specific memoized function β€” a memoized copy of a function has its own independent cache from any other memoized copy.
  • JSON.stringify(args) is a simple, common cache-key strategy, but only works when the arguments are themselves JSON-safe (recall JSON.parse() and JSON.stringify()) and order-sensitive equality is acceptable; a Map keyed on a single non-primitive argument directly (rather than a stringified key) is an alternative worth reaching for when arguments aren’t easily stringified.
  • An unbounded cache grows forever for a function called with ever-changing arguments β€” a cache eviction strategy (a maximum size, an expiry) matters for long-running processes.

Common mistakes

  • Memoizing an impure function (one with side effects, or whose result depends on something besides its arguments) β€” the cache will return a stale or simply wrong result on a later call.
  • Memoizing a cheap function, adding cache-lookup overhead without a meaningful performance benefit.

Runtime notes

A coding pattern built on core ECMAScript (closures, Map), behaving identically anywhere JavaScript runs.

Taught in these lessons

Related reference

Updated 2026-09-03