In JavaScript, it’s commonly used for:

  • Recursive functions (like Fibonacci)
  • Heavy calculations
  • Repeated API/data processing

Join the software development bootcamp.

The Idea (Simple)

Instead of recalculating:

f(10) → compute again  
f(10) → compute again  
f(10) → compute again  

With memoization:

Join thousands already learning how to code online

f(10) → compute once  
f(10) → return stored result  
f(10) → return stored result  

Basic Example (Without Memoization)

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

This is slow because it recomputes the same values many times.

With Memoization

function memoizedFib() {
  const cache = {}; // memory store

  return function fib(n) {
    if (n in cache) return cache[n]; // return saved result

    if (n <= 1) return n;

    const result = fib(n - 1) + fib(n - 2);
    cache[n] = result; // save result
    return result;
  };
}

const fib = memoizedFib();
fib(40); // much faster

What’s Happening?

  1. cache stores previous results.
  2. Before computing, the function checks:
    • “Have I solved this before?”
  3. If yes → return it instantly.
  4. If no → compute and store it.

Generic Memoization Function

function memoize(fn) {
  const cache = {};

  return function (...args) {
    const key = JSON.stringify(args);

    if (cache[key]) {
      return cache[key];
    }

    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

Usage:

const slowAdd = (a, b) => a + b;
const fastAdd = memoize(slowAdd);

fastAdd(3, 4); // calculated
fastAdd(3, 4); // from cache

Why Developers Love Memoization

  • Performance boost
  • Avoids duplicate work
  • Widely used in React (useMemo, useCallback)
  • Critical in algorithms & dynamic programming

One-Liner Definition

Memoization is caching function results so the same computation is never done twice.

Recent Posts

UI/UX Design — Explained Like You’re 5

Download the Codeflare iOS app and learn on the Go 1. What UI and UX…

7 days ago

Costly Linux Mistakes Beginners Make

1. Running Everything as Root One of the biggest beginner errors. Many new users log…

1 month ago

How Keyloggers Work

A keylogger is a type of surveillance software or hardware that records every keystroke made…

1 month ago

CSS Container Queries: Responsive Design That Actually Makes Sense

For years, responsive design has depended almost entirely on media queries. We ask questions like: “If…

2 months ago

Cron Jobs & Task Scheduling

1. What is Task Scheduling? Task scheduling is the process of automatically running commands, scripts,…

2 months ago

Differences Between a Website and a Web App

Here’s a comprehensive, clear differentiation between a Website and a Web App, from purpose all the…

2 months ago