All posts
postApril 16, 2026

What is Memoization?

#javascript#memoization#performance#functional
What is memoization and how do you implement it in JavaScript?

Memoization caches the return value of a function based on its arguments. On repeated calls with the same arguments, it returns the cached result instead of recomputing. ```js 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; }; } const slowFib = n => n <= 1 ? n : slowFib(n-1) + slowFib(n-2); const fastFib = memoize(slowFib); fastFib(40); // computed fastFib(40); // instant from cache ``` Use when: a function is pure, computationally expensive, and called repeatedly with the same arguments.