# Memoization

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-memoization
Last updated: 2026-11-28

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

- **Recursive algorithms with overlapping subproblems**: naive Fibonacci is O(2^n); memoized it becomes O(n). This is top-down dynamic programming, the same idea behind many DSA interview problems.
- **Expensive pure computations**: parsing, formatting large numbers in the Indian system (`Intl.NumberFormat('en-IN')` instances are worth caching), derived data in a UI.
- **Deduplicating async calls**: cache the promise, not the resolved value, so ten components asking for the same user profile trigger one network request.
- **UI frameworks**: React's `useMemo`, `useCallback` and `React.memo`, and selector libraries like Reselect, are memoization tools. React Compiler (stable in 2025) now inserts much of this automatically.

### When memoization hurts

- **Impure functions**: memoizing `getCurrentPrice()` or anything reading `Date.now()` or a database returns stale data.
- **Cheap functions**: if the work is cheaper than building the key and doing the lookup, memoizing makes it slower.
- **Unbounded caches**: every unique input stays in memory forever. A long-running Node.js server memoizing by user ID will slowly leak. Use an LRU (least recently used) cache with a size limit, or a TTL.
- **Rejected promises**: if you cache a promise that rejects, every later caller gets the same failure. Delete the entry on rejection.
- **Mutable arguments**: if a caller mutates an object after the result was cached by identity, the cache returns a result for the old contents.

### Memoization vs general caching

| 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 |

**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

- Memoization caches results by arguments and is only correct for pure functions.
- The cache lives in a closure; the key strategy (primitive, JSON string, WeakMap identity) is the main design decision.
- It turns exponential recursion like naive Fibonacci into linear time.
- Unbounded caches leak memory in long-running processes; use LRU or TTL limits.
- For async work, cache the promise to deduplicate requests and evict it on rejection.

## Common follow-up questions

- How would you memoize a function that takes an object argument without leaking memory?
- How is memoization related to dynamic programming?
- What is the difference between useMemo and React.memo?
- How would you add a TTL to your memoize function?
- Why is JSON.stringify a weak cache key in some cases?

## Interview tips

- Write the memoize function from memory, including fn.apply(this, args) so methods still work.
- Always state the precondition: the function must be pure.
- Mention cache growth and eviction; interviewers at product companies care about production behaviour, not just the happy path.

## Concepts covered

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

Previous: [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition) · Next: [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Deep Cloning: structuredClone vs JSON](https://www.internhack.in/learn/interview/javascript-interview/js-structuredclone)
- [JavaScript Design Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-design-patterns)
- [Memory Leaks in JavaScript](https://www.internhack.in/learn/interview/javascript-interview/js-memory-leaks)
- [Custom Error Types and Error Handling](https://www.internhack.in/learn/interview/javascript-interview/js-error-types)
- [WebSockets and Real-time Communication](https://www.internhack.in/learn/interview/javascript-interview/js-websockets)
- [Advanced Regular Expressions](https://www.internhack.in/learn/interview/javascript-interview/js-regex-advanced)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
