How to write a simple code of Memoization function in JavaScript ?
Last Updated :
17 Apr, 2023
Memoization is a programming technique that we used to speed up functions and it can be used to do whenever we have an expensive function ( takes a long time to execute). It relies on the idea of cache {}. A cache is just a plain object. It reduces redundant function expression calls.
Let's understand how to write a simpler code of the Memoization function in JS.
Example 1: In this example, we will see the inefficient way of writing a function that takes more time to compute.
JavaScript
const square = (n) => {
let result = 0;
// Slow function
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
return result;
}
console.log(square(10000006));
console.log(square(40));
console.log(square(5));
Output:

For this reason, to compute operation in less time for large, we use memoization.
There are two ways to do memoization:
- Function memoization
- Cache memoization
Slow function which takes a large time to compute using cache memoization.
Example 2: This example is used to find the Square of number
JavaScript
const preValues = []
function square(n) {
if (preValues[n] != null) {
return preValues[n]
}
let result = 0;
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result += 1;
}
}
// Storing precomputing value
preValues[n] = result;
return result;
}
console.log(square(50000));
console.log(square(5000));
console.log(square(500));
Output2500000000
25000000
250000
Uses in Dynamic programming using cache memoization.
Example 3: This example is used to print Fibonacci sequence
JavaScript
fib = (n, preValues = []) => {
if (preValues[n] != null)
return preValues[n];
let result;
if (n <= 2)
result = 1;
else
result = fib(n - 1, preValues) + fib(n - 2, preValues);
preValues[n] = result;
return result;
}
console.log(fib(100));
Output354224848179262000000
Using memoizer i.e. it takes a function and then it has to return a function.
Example 4: This example shows memoization in JavaScript
JavaScript
// Memoizer
const memoize = () => {
// Create cache for results
// Empty objects
const results = {};
// Return function which takes
// any number of arguments
return (...args) => {
// Create key for cache
const argsKey = JSON.stringify(args);
// Only execute func if no cached val
// If results object does not have
// anything to argsKey position
if (!results[argsKey]) {
results[argsKey] = func(...args)
}
return results[argsKey];
};
};
// Wrapping memoization function
const multiply = memoize((num1, num2) => {
let total = 0;
for (let i = 0; i < num1; i++) {
for (let j = 0; j < num1; j++) {
// Calculating square
total += 1 *;
}
}
// Multiplying square with num2
return total * num2;
});
console.log(multiply(500, 5000));
Output:
1250000000
Similar Reads
How to write a function in JavaScript ? JavaScript functions serve as reusable blocks of code that can be called from anywhere within your application. They eliminate the need to repeat the same code, promoting code reusability and modularity. By breaking down a large program into smaller, manageable functions, programmers can enhance cod
4 min read
How to Store an Object sent by a Function in JavaScript ? When a function in JavaScript returns an object, there are several ways to store this returned object for later use. These objects can be stored in variables, array elements, or properties of other objects. Essentially, any data structure capable of holding values can store the returned object. Tabl
2 min read
How to transform String into a function in JavaScript ? In this article, we will see how to transform a String into a function in JavaScript. There are two ways to transform a String into a function in JavaScript. The first and easy one is eval() but it is not a secure method as it can run inside your application without permission hence more prone to th
3 min read
How a Function Returns an Object in JavaScript ? JavaScript Functions are versatile constructs that can return various values, including objects. Returning objects from functions is a common practice, especially when you want to encapsulate data and behavior into a single entity. In this article, we will see how a function returns an object in Jav
3 min read
Function that can be called only once in JavaScript In JavaScript, you can create a function that can be called only once by using a closure to keep track of whether the function has been called before. JavaScript closure is a feature that allows inner functions to access the outer scope of a function. Closure helps in binding a function to its outer
3 min read