Memoization — Complete Guide
Memoization — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of JavaScript Tutorial on Toolliyo Academy.
On this page
JavaScript Tutorial · Lesson 73 of 100
Memoization
Basics ✓ → Objects & data ✓ → Async & DOM ✓ → Advanced ✓ → Tools → Projects
Advanced · 5 — Testing & tools · ~10 min · JS Performance & Security
What is this?
Memoization caches function results for the same inputs — trade memory for speed.
Why should you care?
Expensive pure calculations (fibonacci, filters) run once per unique input.
See it live — copy this example
Paste into an HTML file or the browser console (F12). Use Run below when the live editor is available.
function memoize(fn) {
const cache = new Map();
return function (key) {
if (cache.has(key)) return cache.get(key);
const result = fn(key);
cache.set(key, result);
return result;
};
}
const slowDouble = memoize((n) => n * 2);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- First call computes; second call with same key returns cached value.
Practice next
- Run memoize on slowDouble twice with same key.
- Log when computation runs vs cache hit.
- Use only on pure functions.
- Memoize fibonacci with Map and compare call count to naive version.
- Clear cache after 100 entries in custom memoize wrapper.
Remember
Cache by input Pure functions only useMemo in React
ScriptVerse pricing rules
Expensive tax calculation memoized by cart hash so re-renders do not recompute unchanged carts.
Outcome: Memoization trades memory for CPU on hot pure functions in dashboards.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!