DEV Community

Jenish Dabhi
Jenish Dabhi

Posted on

Optimizing JavaScript Functions with Memoization

Memoization is a powerful optimization technique used to speed up function calls by caching previously computed results. This is particularly useful for functions that perform expensive calculations or recursive operations. In this blog post, we’ll explore the concept of memoization in JavaScript with a practical example.

What is Memoization?
A memorized function is a technique where the results of function calls are cached so that repeated calls with the same arguments return the cached result instead of recomputing the output.

Example: Fibonacci Sequence

function memoizedFibonacci() {
    const cache = {};

    return function fib(n) {
        if (n in cache) return cache[n];
        if (n <= 1) return n;

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

const fibonacci = memoizedFibonacci();

console.log(fibonacci(10)); // Output: 55
console.log(fibonacci(50)); // Output: 12586269025
Enter fullscreen mode Exit fullscreen mode

How It Works

1. Cache Initialization: We create a cache object to store previously computed Fibonacci numbers.
**2. Closure: **The fib function is returned from memoizedFibonacci, allowing it to access the cache variable.

3.Check Cache
Before performing the calculation, we check if the result is already in the cache. If it is, we return the cached value.
4. Store Result: If the result is not cached, we compute it, store it in the cache, and then return it.

Benefits of Memoization

  • Performance Improvement: Reduces the number of function calls, leading to faster execution times.

  • Simplicity: Easy to implement and understand, especially for recursive functions.

Quadratic AI

Quadratic AI – The Spreadsheet with AI, Code, and Connections

  • AI-Powered Insights: Ask questions in plain English and get instant visualizations
  • Multi-Language Support: Seamlessly switch between Python, SQL, and JavaScript in one workspace
  • Zero Setup Required: Connect to databases or drag-and-drop files straight from your browser
  • Live Collaboration: Work together in real-time, no matter where your team is located
  • Beyond Formulas: Tackle complex analysis that traditional spreadsheets can't handle

Get started for free.

Watch The Demo 📊✨

Top comments (0)

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay