What is Memoization in JavaScript?

What is Memoization in JavaScript?
January 30, 2023

Memoization is required because it optimizes the performance of slow or expensive functions by reducing the number of times they need to be executed.

For example, in financial calculations, if the same mathematical formula is used multiple times, memoization can be used to cache the result of the formula, reducing the calculation time and increasing the overall efficiency of the application.

Memoization is a technique in JavaScript where the result of a function is stored in the cache to avoid redundant computation when the function is called again with the same arguments.

The idea is to store the results of a function in a cache, keyed by its arguments, so that the next time the function is called with the same arguments, the result can be immediately retrieved from the cache instead of being recomputed.

Let's take an example, you are writing a program to calculate returns for your stock market application, At that time you can use memorization as follows.

function memoize(fn) {

  const cache = {};

  return function(...args) {

    if (cache[args]) {
      return cache[args];
    }

    const result = fn.apply(this, args);
    cache[args] = result;

    return result;

  };
}


const returnsCalculator = memoize(function(principal, interest, years) {

  if (years === 0) return principal;

  return returnsCalculator(principal * (1 + interest), interest, years - 1);

});


const principal = 1000;
const interest = 0.05;
const years = 5;

console.log(returnsCalculator(principal, interest, years));


let's understand the above code:

Are preparing for Front-End Developer Job? Click here to get the front-end developer interview kit to prepare for your next interview


Resources for You

ChatGPT Guide For Software Developers

Learn to use ChatGPT to stay ahead of competition

Front-End Developer Interview Kit

Today, Start preparing to get your dream job!

JavaScript Developer Kit

Start your JavaScript journey today!

Master JavaScript by Solving Daily Challenges

Challenge Yourself Daily: Advance Your JavaScript Skills and Career

View Challenges

Newsletter for Developers!

Join our newsletter to get important Web Development and Technology Updates