Speed Up Your JavaScript Code with Memoization: Caching Trick for Faster Function Calls

Kok Hang Cheng
3 min readMar 27, 2023

Memoization is a powerful technique in JavaScript that allows you to cache the results of expensive function calls and avoid re-computing them every time they’re called with the same input parameters. This can save time and computing resources, making your code faster and more efficient.

Here’s a real-life coding example to show you how Memoization works:

Let’s say you have a function that calculates the factorial of a number:

function factorial(num) {
if (num === 1 || num === 0) {
return 1;
}
return num * factorial(num - 1);
}

This function works fine for small values of num, but for large values, it can take a long time to compute. Instead of re-computing the factorial every time the function is called, you can use Memoization to store the results in a cache and retrieve them when the function is called with the same input parameter.

function memoize(func) {
var cache = {};
return function(num) {
if (num in cache) {
console.log("Result retrieved from cache!");
return cache[num];
} else {
var result = func(num);
cache[num] = result;
console.log("Result not found in cache. Calculating...");
return result;
}
}
}

// Wrap the factorial…

--

--