AceDevHub
Intermediate JavaScript Interview QuestionsIntermediateScenario

JavaScript · Question 69

What is memoization, and what pitfalls should you consider when memoizing JavaScript functions?

Direct answer

Memoization caches a function result for previously seen inputs, which can save repeated expensive work when the function is deterministic enough, but cache-key correctness, memory growth, invalidation, and object identity must be designed deliberately.

A simplistic memoizer that stores cache[arg] works only for a narrow input domain. Real functions may accept multiple arguments, objects, symbols, or values whose string representations collide.

  • Correctness — memoizing an impure function or one that depends on time, global state, locale, permissions, or mutable inputs can return stale/wrong results.
  • Key design — object arguments may need identity-based Map/WeakMap structures or a stable domain-specific key.
  • Memory — an unbounded cache can become a memory leak; consider LRU, TTL, size limits, or weak keys depending on the use case.
  • Cost — hashing/serialization and cache lookups can cost more than recomputing cheap functions.

Memoization is most attractive when repeated calls with equivalent inputs are common and the saved computation is meaningfully more expensive than cache maintenance.