In JavaScript, it’s commonly used for:
Join the software development bootcamp.
Instead of recalculating:
f(10) → compute again
f(10) → compute again
f(10) → compute again With memoization:
Join thousands already learning how to code online
f(10) → compute once
f(10) → return stored result
f(10) → return stored result function fib(n) {
if (n <= 1) return n;
return fib(n - 1) + fib(n - 2);
} This is slow because it recomputes the same values many times.
function memoizedFib() {
const cache = {}; // memory store
return function fib(n) {
if (n in cache) return cache[n]; // return saved result
if (n <= 1) return n;
const result = fib(n - 1) + fib(n - 2);
cache[n] = result; // save result
return result;
};
}
const fib = memoizedFib();
fib(40); // much faster
cache stores previous results.function memoize(fn) {
const cache = {};
return function (...args) {
const key = JSON.stringify(args);
if (cache[key]) {
return cache[key];
}
const result = fn(...args);
cache[key] = result;
return result;
};
} Usage:
const slowAdd = (a, b) => a + b;
const fastAdd = memoize(slowAdd);
fastAdd(3, 4); // calculated
fastAdd(3, 4); // from cache useMemo, useCallback)Memoization is caching function results so the same computation is never done twice.
Latest tech news and coding tips.
A SOC Analyst (Security Operations Center Analyst) is one of the frontline defenders of an organization’s cybersecurity…
Most image upload systems assume one thing: the user has a stable internet connection. That assumption…
Imagine a user submits a form while their internet connection suddenly disappears. Normally, the request…
Cybercriminals don't always announce their presence. Many compromises are designed to remain unnoticed for weeks…
For years, jQuery was everywhere. If you were building websites in the 2010s, there was a…
Few things halt a developer’s flow faster than seeing the dreaded word: CONFLICT. A Git merge…