Course contentsShow
← JavaScript
Lesson 2372 of 2,72349. Common Patterns and IdiomsFree lesson

What Is Memoization?

Understanding memoization as caching function results to avoid redundant calculations.

What Is Memoization?

You'll learn how memoization caches function results to avoid repeating expensive calculations.

The Core Idea

Memoization is an optimization technique where you store (cache) the results of function calls based on their arguments. When the same function is called again with the same inputs, you return the cached result instead of recalculating it. Think of it like a chef remembering that yesterday's customer who ordered "medium rare steak with fries" loved it — when the same customer orders the exact same thing today, the chef knows exactly what to prepare without rechecking the recipe.

This pattern is especially valuable when:

  • A function performs expensive calculations
  • The function is called repeatedly with the same arguments
  • The function is pure (same inputs always produce same outputs)

How It Works in Plain English

Imagine a function that calculates something complex. Without memoization, it recalculates every time. With memoization, the first call stores the result in a cache (like a simple object where keys are argument combinations). Subsequent calls check: "Have I seen these arguments before?" If yes, return the cached result instantly. If no, calculate, cache, and return.

When Memoization Shines

You'd use this pattern when:

  • Recursive algorithms (like Fibonacci) recalculate the same values repeatedly
  • Processing large datasets with repetitive computations
  • API responses that rarely change but are frequently requested
  • Complex formatting or parsing operations on the same data

The trade-off: memory usage increases because you're storing results, so it's best for functions with limited unique input combinations.

Key Takeaway: Memoization transforms repeated expensive computations into fast cache lookups by remembering previous results, dramatically improving performance for pure functions with repeated calls.