AI Workshop: learn to build apps with AI →
Advanced JavaScript: Memoization

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Memoization is one technique that lets you considerably speed up 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 the stored result.

It’s caching, for functions.

Why is this useful?

Suppose our function takes one 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.

On every call, if we don’t find the cached result for that number, we perform the calculation. Otherwise, we just return it.

There are libraries that will add the memoization feature to any pure function, so you can skip modifying the function itself and 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