Hiprup

What is memoization in JavaScript?

Memoization caches a function's results so repeated calls with the same inputs return instantly instead of recomputing.

  • How it works — store results in a cache keyed by the arguments; on a repeat call, return the cached value.

  • Best for — pure functions with expensive calculations and repeated inputs.

Trade-off: it spends memory to save time — worth it only when recomputation is costly and inputs recur.

// Simple memoize
function memoize(fn) {
  const cache = new Map();
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn.apply(this, args);
    cache.set(key, result);
    return result;
  };
}

// Without memoization: O(2^n)
function fibonacci(n) {
  if (n < 2) return n;
  return fibonacci(n - 1) + fibonacci(n - 2);
}
// fibonacci(40) takes seconds

// With memoization: O(n)
const memoFib = memoize(fibonacci);
// memoFib(40) is instant

// Practical: expensive API result caching
const fetchUser = memoize(async (id) => {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
});

await fetchUser(1); // Fetches from API
await fetchUser(1); // Returns cached result (no API call)
await fetchUser(2); // Different arg, fetches from API

memoize wraps any function with a cache. JSON.stringify creates a cache key from arguments. Map.has checks for cached results.

The Fibonacci example shows the dramatic improvement: O(2^n) → O(n). The API caching example shows a practical use case. Only works correctly with pure functions (same input = same output).

Implement memoize from scratch — it is a common interview coding question. Show the Fibonacci performance improvement (exponential → linear).

Know the limitation: only works with pure functions. The JSON.stringify key has limitations (objects with same content but different order produce different keys).

What is memoization in JavaScript? | Hiprup