Skip to content

Memoization in JavaScript

An introduction to memoization in JavaScript

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

It is not a technique unique to JavaScript, although I tagged this post as “JavaScript” because I will provide some JS examples.

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.

Try to run it. I made a Codepen to make it easy to test, which uses document.write() to print to the HTML page (first time I used document.write() in ages, but this time it was useful).

See this example on Codepen: https://codepen.io/flaviocopes/pen/aMbbbP/

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.


→ Get my JavaScript Beginner's Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about js: