🟨 JavaScript Intermediate

What is memoization in JavaScript?

Answer

Memoization is an optimization technique where function results are cached by their input, so repeated calls with the same arguments return the cached result instead of recomputing. Useful for pure functions with expensive computations. Simple implementation: 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; }; }. Classic example — memoized fibonacci: const fib = memoize(n => n <= 1 ? n : fib(n-1) + fib(n-2)). Reduces time complexity from O(2^n) to O(n). Trade-off: faster execution at the cost of memory. Use when: the function is pure (same inputs always give same output), calls are expensive (computation, API), and the same inputs are likely to repeat. Lodash provides _.memoize(). In React, useMemo and useCallback hooks memoize values and functions.