JavaScript Q&A Logo
JavaScript Q&A Part of the Q&A Network

How does memoization work in JavaScript?

Asked on Sep 02, 2024

Answer

Memoization in JavaScript is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again. This can significantly improve performance for functions with costly computations.
<!-- BEGIN COPY / PASTE -->
        function memoize(fn) {
            const cache = new Map();
            return function(...args) {
                const key = JSON.stringify(args);
                if (cache.has(key)) {
                    return cache.get(key);
                }
                const result = fn(...args);
                cache.set(key, result);
                return result;
            };
        }

        // Example usage
        const slowFunction = (num) => {
            console.log("Computing...");
            return num * 2;
        };

        const fastFunction = memoize(slowFunction);

        console.log(fastFunction(5)); // Computing... 10
        console.log(fastFunction(5)); // 10 (cached result)
        <!-- END COPY / PASTE -->
Additional Comment:
  • The "memoize" function takes another function "fn" as an argument and returns a new function that caches results.
  • A "Map" is used to store cached results, with the JSON stringified arguments as the key.
  • When the memoized function is called, it checks if the result is already in the cache. If so, it returns the cached result; otherwise, it computes the result, caches it, and then returns it.
  • This technique is useful for functions with expensive computations that are called multiple times with the same arguments.
✅ Answered with JavaScript best practices.
← Back to All Questions