Open In App

What is Memoization in JavaScript ?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Memoization is an optimization technique used in computer programming to store the results of expensive function calls and return the cached result when the same inputs occur again. This can help to improve performance by avoiding redundant calculations. In JavaScript, memoization can be implemented using closures or by leveraging data structures like objects or maps to store previously computed results.

Example: Here, The fibonacci function takes an integer n as input, representing the position in the Fibonacci sequence to compute. Inside the function, it first checks if the result for the given n is already cached in the memo object. If it is, it returns the cached result. If the result is not cached, it calculates the Fibonacci number recursively by calling itself with the two previous Fibonacci numbers (n - 1 and n - 2) and stores the result in the memo object. Finally, it returns the computed Fibonacci number.

Javascript




function fibonacci(n, memo = {}) {
    if (n in memo) {
        // If result is already cached, return it
        return memo[n];
    }
 
    if (n <= 2) {
        // Base cases for Fibonacci sequence
        return 1;
    }
 
    // Calculate Fibonacci number
    //  recursively and cache the result
    memo[n] = fibonacci(n - 1, memo)
        + fibonacci(n - 2, memo);
 
    return memo[n];
}
 
// Test the memoized Fibonacci function
console.log(fibonacci(6));
console.log(fibonacci(10));
console.log(fibonacci(20));


Output

8
55
6765

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads