Course contentsShow
← JavaScript
Lesson 2381 of 2,72349. Common Patterns and IdiomsFree lesson

Memoization Gotchas with Impure Functions

Understanding why memoization fails with side effects or time-dependent logic.

Memoization Gotchas with Impure Functions

You'll learn why memoization breaks when functions have side effects or depend on changing external state.

The Core Problem

Memoization assumes a pure function: same inputs always produce the same output. When a function is impure—meaning it depends on external state, causes side effects, or uses time-dependent logic—caching can return stale results or skip important operations entirely.

Think of it like caching a weather forecast. If you memoize "What's today's weather?" and use Monday's answer on Tuesday, you'll get the wrong forecast. The question looks the same, but the answer changes over time.

Common Gotchas

Time-Dependent Logic

const memoize = (fn) => {
  const cache = new Map();
  return (arg) => {
    if (cache.has(arg)) return cache.get(arg);
    const result = fn(arg);
    cache.set(arg, result);
    return result;
  };
};

const getGreeting = memoize((name) => {
  const hour = new Date().getHours();
  return hour < 12 ? `Good morning, ${name}` : `Good afternoon, ${name}`;
});

console.log(getGreeting('Alice')); // "Good morning, Alice" at 10am
// Hours later...
console.log(getGreeting('Alice')); // Still returns "Good morning" — wrong!

Side Effects

let counter = 0;
const trackAndDouble = memoize((x) => {
  counter++; // Side effect: increments external state
  return x * 2;
});

trackAndDouble(5); // counter = 1
trackAndDouble(5); // Returns cached 10, but counter stays 1 (side effect skipped!)

Key Takeaway: Only memoize pure functions with no side effects, external dependencies, or time-based logic—otherwise your cache will serve outdated or incorrect results while silently skipping important operations.