What is Memoization in JavaScript?
Learn what memoization is in JavaScript, how caching function results boosts performance, with a reusable memoize helper and memoized Fibonacci example.
Expected Interview Answer
Memoization is an optimization technique that caches the results of expensive function calls and returns the cached result when the same inputs occur again, avoiding repeated computation.
A memoized function stores each computed result in a cache keyed by its arguments. On the next call with identical inputs, it skips the work and returns the stored value. It only helps for pure functions whose output depends solely on their inputs, and it trades memory for speed, so the cache must be managed to avoid unbounded growth.
- Avoids recomputing expensive results for repeated inputs
- Speeds up recursive algorithms like Fibonacci
- Reduces redundant network or CPU work
- Improves perceived performance in UI rendering
- Simple to add around any pure function
AI Mentor Explanation
Memoization is like a scorer keeping a card of each bowler's figures. When the captain asks a bowler's economy rate mid-over, the scorer reads it off the card instead of re-tallying every delivery. The heavy counting is done once and stored, so repeat questions are answered instantly from the saved figure.
Step-by-Step Explanation
Step 1
Wrap the target function
Create a higher-order function that returns a memoized version of the original.
Step 2
Build a cache
Use a Map or plain object to store results keyed by the function's arguments.
Step 3
Check the cache first
On each call, generate a key from the arguments and look it up before computing.
Step 4
Compute and store on a miss
If the key is absent, run the original function and save the result under that key.
Step 5
Manage the cache
Bound the cache size or clear it when appropriate to prevent memory leaks.
What Interviewer Expects
- A definition tying memoization to caching results by input
- Recognition that it only suits pure functions
- Awareness of the memory-for-speed trade-off
- A working implementation with a cache and key generation
- A concrete example such as memoized Fibonacci
Common Mistakes
- Memoizing impure functions whose output depends on external state
- Using an unbounded cache that grows forever and leaks memory
- Generating cache keys that collide for different arguments
- Assuming memoization always speeds things up even for cheap functions
- Ignoring reference-type arguments when serializing keys
Best Answer (HR Friendly)
“Memoization means remembering the answer to a calculation so you do not have to redo it. The first time a function runs with certain inputs it saves the result, and next time those same inputs appear it hands back the saved answer instantly.”
Code Example
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 slowSquare = (n) => {
for (let i = 0; i < 1e6; i++) {} // pretend expensive
return n * n;
};
const fastSquare = memoize(slowSquare);
console.log(fastSquare(9)); // computed: 81
console.log(fastSquare(9)); // cached: 81const fib = memoize(function (n) {
return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(40)); // 102334155, computed fast thanks to cachingFollow-up Questions
- Why does memoization only work reliably for pure functions?
- How would you prevent a memoization cache from growing without bound?
- What are the risks of using JSON.stringify to build cache keys?
- How does memoization relate to dynamic programming?
- When would memoization actually hurt performance?
MCQ Practice
1. What does memoization primarily trade to gain speed?
Memoization stores results in a cache, spending additional memory to avoid recomputation and gain speed.
2. Memoization is only safe to apply to which kind of function?
A pure function's output depends only on its inputs, so cached results stay correct for identical arguments.
3. Which structure is commonly used as the memoization cache?
A Map (or object) keyed by the serialized arguments lets the function look up whether a result already exists.
Flash Cards
Define memoization. — Caching a function's results by input so repeated calls with the same inputs return instantly.
What kind of function can be safely memoized? — A pure function, whose output depends only on its arguments.
What is the main trade-off? — Extra memory used by the cache in exchange for saved computation time.
A classic memoization example? — Fibonacci, where caching sub-results turns exponential work into linear work.