How to write a simple code of Memoization function in JavaScript?


Memoization is the optimization technique to improve the performance of the function. Before we start with the memoization technique, let’s understand why we require it using the example below.

Example (Naïve approach to finding Fibonacci number)

In the example below, we have implemented the naïve approach to find the nth Fibonacci number. We used the recursive approach to find the nth Fibonacci series.

<html>
<body>
   <h3>Finding the nth Fibonacci using recursive approach number in JavaScript</h3>
   <p>Enter the number to find the nth Fibonacci number.</p>
   <input type = "number" id = "fib"> <br>
   <div id = "content"> </div> <br>
   <button onclick = "executeFunc()"> Submit </button>
   <script>
      let content = document.getElementById('content');
      
      // function to write the fibonacci series
      function findFib(n) {
         if (n <= 1) return n;
         return findFib(n - 1) + findFib(n - 2);
      }
      function executeFunc() {
         let n = document.getElementById('fib').value;
         content.innerHTML = "The " + n + "th fibonacci number is " + findFib(n);
      } 
   </script>
</body>
</html>

The above example works fine for small input values like less than 1000, but when we enter the input value of range 104, it takes more time than usual, and for the input of range 106, it crashes the browser due to memory being out of bounds.

We can use the memoization technique to optimise the above code, which allows us to store the previously calculated results. For example, to find the 4th Fibonacci number, we need to find the 3rd and 2nd Fibonacci numbers. Again, to find 3rd Fibonacci number, we must find the 2nd and 1st Fibonacci numbers. So, here we have calculated the 2nd Fibonacci number twice.

Now, think that you want to find the Fibonacci number for a large nth value, and you can think how much repetition it requires. So, for optimization purposes, we can calculate the 2nd Fibonacci number for the first time and store it in the temporary variable. After that, when we require to calculate the 2nd Fibonacci number again, we can access it from the array, making the code more efficient.

Also, storing previously calculated results in the array for later use is memoization.

Syntax

Users can follow the syntax below to implement the memorization to find the nth fibonacci number.

if (temp[n]) return temp[n];
if (n <= 1) return n;
return temp[n] = findFib(n - 1, temp) + findFib(n - 2, temp);

In the above syntax, we first check if the nth Fibonacci number already exists in the ‘temp’ object, then we return the value; otherwise, we calculate its value and stit ore to the temp object.

Approach

Step 1 – Use the if statement to check if results for n exist in the temp object. If yes, return the previously calculated values.

Step 2 – If n is less than or equal to 1, return 1 as a base case for the recursive function.

Step 3 – Calculate the n-1, and n-2 fibonacci numbers, add them and store them in the temp object for later use.

Step 4 – Return the nth Fibonacci number to the temp object after storing it.

Example (Finding nth Fibonacci number using memoization)

Using the memorisation technique, we have optimized the first example’s code in the below example. We have used the temp object to store the previously calculated results. In the output, users can observe that the below code is more efficient than the first example’s code.

<html>
<body>
   <h3>Finding the nth Fibonacci number using memoization using extra space in JavaScript</h3>
   <p>Enter the number to find the nth Fibonacci number.</p>
   <input type = "number" id = "fib"> <br>
   <div id = "content"> </div> <br>
   <button onclick = "start()"> Submit </button>
   <script>
      let content = document.getElementById('content');
      function findFib(n, temp) {
         if (temp[n]) return temp[n];
         if (n <= 1) return n;
         return temp[n] = findFib(n - 1, temp) + findFib(n - 2, temp);
      } 
      function start() {
         let n = document.getElementById('fib').value;
         content.innerHTML = "The " + n + "th fibonacci number using memoization is " + findFib(n, {}) + "<br>";
      }
   </script>
</body>
</html>

Approach: Using memoization without using extra space

Step 1 – Initialize the a with 0 and b with 1.

Step 2 – Use the for loop making n iterations to find the nth Fibonacci number.

Step 3 – Here, c is a temporary variable storing the (i-1)th Fibonacci number.

Step 4 – Store the value of the b variable in a.

Step 5 – Store the value of variable c in variable b.

Example

The below example is also an optimized variant of the first example. In the second example, we used the temp object to store previously calculated results, but in the below code, we used the single temporary variable called c.

The below code is the most efficient approach to finding the Fibonacci series as its time complexity is of O(n), and space complexity is of O(1).

<html>
<body>
   <h3>Finding the nth Fibonacci number using memoization in JavaScript</h3>
   <p>Enter the number to find the nth Fibonacci number:</p>
   <input type = "number" id = "fib"> <br>
   <div id = "content"> </div> <br>
   <button onclick = "findFib()"> Submit </button>
   <script>
      let content = document.getElementById('content');
      
      // function to write the fibonacci series
      function findFib() {
         let n = document.getElementById('fib').value;
         let a = 0, b = 1, c;
         if (n == 0) {
            return a;
         }
         for (let i = 2; i <= n; i++) {
            c = a + b;
            a = b;
            b = c;
         }
         content.innerHTML += "The " + n + "th Fibonacci number using memoization is " + b;
      }
   </script>
</body>
</html>

In this tutorial, we learned about the memorization technique to optimize the codes to make them more time and space efficient. Users can see how we have optimized the first example’s code in the second and third examples using different algorithms.

Updated on: 01-Mar-2023

216 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements