Published Mar 26, 2022Updated Mar 27, 2022
Contribute to Docs

In JavaScript, memoization can be used to improve a program’s performance.

This is ideal whenever the same calculations (with the same inputs and outputs) are known to take place. Memoization helps by saving, or caching, these results in computer memory for later use. It can be applied to many contexts, including:

  • Making calls to recursive or pure functions where some calculations use the same inputs and return the same outputs.
  • Fetching from the server with the same base API endpoints.


memo = []

function memoFunction(arg) {
  if(memo[arg]) {
    return memo[arg]
  } else {
    // Do this and update memo.

Memoized results can be represented with arrays or objects. In a given function, if a previously calculated result exists in the memo array, it is returned. Otherwise, normal calculations take place and the memo array is updated.


In the example below, the getSquare() function accepts a parameter n and returns the square of it. With small inputs, this function takes little to no time to process. But as the inputs get larger, the timelapse becomes more noticeable. This point is further shown with the calls to console.time() and console.timeEnd().

To address this, memoization is used in the getSquareMemo() function where such calculations are skipped if they have already been made and stored in memo.

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn JavaScript on Codecademy