Memoization in JavaScript

An introduction to memoization in JavaScript

⭐️ 👀 2023 WEB DEVELOPMENT BOOTCAMP starting in days! Join the waiting list to reserve your spot in my 10-weeks cohort course and learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much much more! 👀 ⭐️

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 the Pen Memoization example factorial by Flavio Copes (@flaviocopes) on CodePen.

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.

One more thing! ⚠️ ✋

At the end of January I will organize the Web Development Bootcamp.

It's a 10-weeks long cohort online course where I will guide you to becoming a Web Developer.

It's not "just a course". It's a big event I organize once a year.

We'll start from zero, learn the fundamentals of Web Development, HTML CSS, JavaScript, Tailwind, Git, using the command line, VS Code, GitHub, Node.js, we'll then learn React, JSX, how to use PostgreSQL, Astro, Next.js, Prisma, deploying on Netlify/DigitalOcean/Fly/Vercel and much more! 

At the end of the first 10 weeks you'll know how to create web sites and web applications and I'll unlock you the 2nd phase of the Bootcamp: you will get access to a large number of projects exclusive to the Bootcamp graduates, so you can follow my instructions to build things like private areas with authentication, clones of popular sites like Twitter YouTube Reddit, create e-commerce sites, and much much more.

Because once you got the fundamentals, you only learn by working on real, exciting projects.

To find out more, visit