DEV Community

DIWAKARKASHYAP
DIWAKARKASHYAP

Posted on • Updated on

Memorization in JS(javascript)

Memorization is a crucial technique in programming languages, optimizing applications by reusing computed results and eliminating redundant calculations. This boosts efficiency and improves speed. Leveraging memorization empowers developers to enhance code performance, making it more efficient and faster, ultimately improving overall application quality.

Memorization in JavaScript revolves around two key concepts:

1- Closures: These are functions that retain access to variables defined in their outer scope, even after the outer function has completed execution.

2- Higher Order Functions: These functions can accept other functions as arguments and/or return results. They enable advanced functional programming techniques like composition and abstraction.

Memorization can be applied to any function. Let's explore some examples below:
Example

write code for factorial of "n" number. ( if you don't know about Factorial, for example, the factorial of 5 is calculated as 5 )

Do without memorization

const factorial = (n)=>{
    let answer=1
    for (let i = 1; i <= n; i++) {
        answer = answer*i ;
    }
    console.log(answer);
}

factorial(n); //where n is any number
Enter fullscreen mode Exit fullscreen mode

Do with memorization

const factorial = (n) => {
    let previousCalculation = {};
    if (previousCalculation.n != undefined) {
        console.log(previousCalculation.n);
    } else {
        let answer = 1;
        for (let i = 1; i <= n; i++) {
            answer = answer * i;
        }

        previousCalculation.n = answer;
        console.log(answer);
    }
};

factorial(n); //where n is any number
Enter fullscreen mode Exit fullscreen mode

To optimize calculations, the "previousCalculation" object can be utilized. If an input number already exists as a key in this object, the associated value is retrieved, avoiding the need for a "for" loop and saving valuable time. In case the input value is not found, the loop executes, storing the number (n) as a key and its corresponding answer as the value in the object. This approach significantly improves efficiency by minimizing redundant computations.

Memorization is particularly beneficial in various scenarios such as API calls, large calculations, dynamic programming, string manipulations, and component re-rendering to obtain specific values.

Thank you for reading! For more insights into advanced concepts of JavaScript and React, feel free to follow me on Twitter: https://twitter.com/Diwakar_766

Top comments (0)