Advanced JavaScript: Memoization

Join the AI Workshop to learn more about AI and how it can be applied to web development. Next cohort February 1st, 2026

The AI-first Web Development BOOTCAMP cohort starts February 24th, 2026. 10 weeks of intensive training and hands-on projects.


Memoization is one technique that lets you speed up considerably your applications.

It is not a technique unique to JavaScript, although I’ll provide some JS examples here.

Memoization is the act of storing the result of a function call after we run it, in the function itself. The next time we call the function, instead of performing its “regular” execution once again, it just returns us the stored result.

It’s caching, for functions.

Why is this useful?

Suppose our function takes 1 second to run, while caching lets us speed up the process to 2 milliseconds. There is a clear gain here.

Sounds pretty cool. Where is the catch?

Memoization works if the result of calling a function with the same set of arguments results in the same output. In other words, the function must be pure. Otherwise caching the result would not make sense.

So, database queries, network requests, writing to files and other non-pure operations cannot be optimized with memoization. For those, you will need to find other ways to optimize them. Or just live with their inefficiency, which sometimes is unavoidable.

Let’s create one example:

// Calculate the factorial of num
const fact = num => {
  if (!fact.cache) {
    fact.cache = {}
  }
  if (fact.cache[num] !== undefined) {
    console.log(num + ' cached')
    return fact.cache[num];
  } else {
    console.log(num + ' not cached')
  }
  fact.cache[num] = num === 0 ? 1 : num * fact(num - 1)
  return fact.cache[num]
}

Calculating the factorial of a number. The first time fact() is run, it creates a cache object property on the function itself, where to store the result of its calculation.

Upon every call, if we don’t find the result of the number in the cache object, we perform the calculation. Otherwise we just return that.

There are libraries that will add the memoization feature to any pure function, so you can skip the task of modifying the function itself, but you just decorate it with this functionality.

In particular I mention fast-memoize.

Lodash also has a memoize() method, if you are a Lodash fan.

Lessons in this unit:

0: Introduction
1: Generators
2: Symbols
3: Proxy objects
4: ▶︎ Memoization
5: Functional programming
6: Dynamic imports