HomeJAVASCRIPTExplain memoization in JavaScript.

Explain memoization in JavaScript.

1. What is Memoization?

Memoization is an optimization technique used to speed up functions by storing the results of expensive function calls and returning the cached result when the same inputs occur again.

  • Think of it like remembering the answer to a question you’ve already solved.
  • It’s especially useful for recursive functions or functions with repeated calculations.

2. Why Use Memoization?

Consider a recursive Fibonacci function without memoization:

function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
}

console.log(fibonacci(40)); // Takes a long time
  • The problem: It recalculates the same Fibonacci numbers many times.
  • For example, fibonacci(38) is computed multiple times.

3. Memoized Version

We store the results in a cache object:

function fibonacciMemo(n, cache = {}) {
    if (n in cache) return cache[n]; // Return cached result
    if (n <= 1) return n;

    cache[n] = fibonacciMemo(n - 1, cache) + fibonacciMemo(n - 2, cache);
    return cache[n];
}

console.log(fibonacciMemo(40)); // Much faster

How it works:

  1. Check if the result for n is in the cache.
  2. If yes, return the cached value.
  3. If no, compute it, store it in the cache, and return it.

4. General Memoization Function

You can create a reusable memoizer function:

function memoize(fn) {
    const cache = {};
    return function (...args) {
        const key = args.toString(); // Convert arguments to string for caching
        if (key in cache) return cache[key];
        const result = fn(...args);
        cache[key] = result;
        return result;
    };
}

// Example usage
const factorial = memoize(function fact(n) {
    if (n <= 1) return 1;
    return n * fact(n - 1);
});

console.log(factorial(5)); // 120
console.log(factorial(5)); // Returns instantly from cache

5. Key Points

  • Memoization trades memory for speed.
  • Works best for pure functions (functions with no side effects, same output for same input).
  • Can be applied to recursive algorithms, API calls, or expensive calculations.

If you want, I can also show a real-world example using JavaScript for API call caching, which is a very practical use of memoization.

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *