TechMentorAI

Memoization

in JavaScript

Published

Memoization is an optimization technique used in computer programming to speed up programs by storing the results of expensive function calls and reusing them when the same inputs occur again. Instead of calling a function, it first looks for the result in a cache. If it finds the result in the cache, it retrieves it. If it doesn't, it calls the function, saves the result in a cache, and then returns it. This technique is commonly used in JavaScript as well as other programming languages.

Imagine Memoization in JavaScript

Using Memoization in JavaScript

In JavaScript, memoization can be implemented via closures. A closure is a function that has access to its own scope, the outer (enclosing) function's scope, and the global scope. By taking advantage of this property, one can maintain a cache within a function which gets persisted even after the function's invocation is over.

function memoize(fn) {
  let cache = {};
  return function(...args) {
    let n = args[0];
    if (n in cache) {
      console.log('Fetching from cache');
      return cache[n];
    }
    else {
      console.log('Calculating result');
      let result = fn(n);
      cache[n] = result;
      return result;
    }
  }
}
const factorial = memoize(
  x => {
    if (x === 0) {
       return 1;
    }
    else {
      return x * factorial(x-1);
    }
  }
);
console.log(factorial(5));  // Calculating result
console.log(factorial(5));  // Fetching from cache

Benefits and Drawbacks

Memoization can be very beneficial, particularly in situations where you find yourself calling the same expensive function multiple times with the same complex input. By using memoization, you can significantly speed up your programs by avoiding unnecessary recalculations. However, it's important to note that memoization comes with its own costs. It can cause your memory usage to increase, as the results of function calls are stored and need space. Therefore, it's a technique that should be used judiciously.

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.13 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

Memoization is like having a treasure box where you store answers to questions that you've already solved, so it's easier to find those answers again later. Think of it like this. Let's say you have a favorite superhero comic book that you read many times, and you remember your favorite parts. So, when your friends ask you about it, you can quickly tell them without having to read the whole book again. That's kind of what memoization does!

Imagine Memoization in JavaScript

Why is Memoization useful?

Memoization helps a computer to do less work because it remembers the answers to things it has solved before. Imagine if you had to reread your favorite comic book every time someone asked you about it. That would take a long time, right? But because you remember the favorite parts, you can tell your friends about it fast. That's why memoization is useful - it makes things quicker and easier for the computer.

How does Memoization work in JavaScript?

In JavaScript, we use functions to do things. Sometimes we need functions to do the same thing over and over again. This could make our programs slow if we don't use memoization. With memoization, the first time a function does something, it stores the result in its treasure box (like you with your comic book). Then, if it needs to do that thing again, it can look at the answer in the treasure box instead of doing the whole thing all over again.

function memoize(fn) {
    var cache = {};
    return function(n) {
        if (cache[n]) {
            return cache[n];
        } else {
            let result = fn(n);
            cache[n] = result;
            return result;
        }
    };
}

Remember!

Memoization is a clever way that programmers make things run faster. Sadly, not all problems can use memoization, only those that solve the same thing many times. But when it can be used, it's like a mighty superhero power for JavaScript!

No Time to Read? Learn on the Go!

By reading this article, you've invested 1.45 minutes of your life into expanding your knowledge and perspectives. Now, imagine learning on-the-go, turning every moment into an opportunity for growth and discovery.

To learn more about function optimization in JavaScript, you could read the article on Debouncing and Throttling in JavaScript

About author

Roman Y.
Senior Software Engineer at Nike

Why did I decide to launch this website? Drawing from my rich background in interviewing candidates for a variety of developer roles, I've observed a common pattern: many applicants share similar deficiencies in their knowledge during technical interviews. Motivated by this insight, I established this website with the aim of assisting developers in securing their ideal job. Through straightforward and concise articles, my goal is to not only deepen your understanding of programming language nuances but also to equip you with the insights needed to deliver the precise answers interviewers expect. Essentially, you'll be providing the correct response. I encourage you to spread the word about this site on social media platforms. Echoing the wisdom of an Armenian saying: "Do good and cast it into the water."

EXCLUSIVELY

Certain articles only distributed to subscribers through email