Memorization in JS(javascript)

·

2 min read

Memorization is an essential technique present in all programming languages. It optimizes applications by reusing computed results, eliminating redundant calculations. This boosts efficiency and significantly improves speed. By leveraging memorization, developers can enhance their code's performance, making it more efficient and faster.

basically the memorization in JS works on two concepts i.e

1- Closures: Closures in JavaScript are functions that have access to variables defined in their outer scope, even after the outer function has finished executing.

2- Higher Order Functions: Higher-order functions in Javascript are functions that can accept other functions as arguments and/or return results, enabling powerful functional programming paradigms such as composition and abstraction

You can use memorization in any function, lets check some example -

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

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

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

The best case scenario to use Memorization is in API calls, big calculations, Dynamic programming, string manipulations, and rerendering components to get some values

thank you for reading, please follow me on Twitter https://twitter.com/Diwakar_766 i regularly share advanced concepts of Javascript and react