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

JavaScript vs Your Expectations

Almost everyone starts learning JavaScript with the wrong expectations. Let's fix them. Download the Codeflare…

2 days ago

Introduction to Phaser JS

Phaser JS is a powerful, open-source HTML5 game development framework used for creating 2D games that…

7 days ago

Web Authentication Libraries

JavaScript / Node.js Authentication Libraries 1. Passport.js One of the most popular authentication middleware libraries…

1 week ago

The Things They Carry: Software Developers Starter Packs

Every profession comes with its own set of tools. A carpenter has a toolbox, a…

1 week ago

CRUD Operations: The Foundation of Data Management

Every application that stores and manages data relies on a set of basic operations known…

3 weeks ago

Common PHP Mistakes Every Developer Should Avoid

PHP remains one of the most widely used server-side programming languages, powering platforms such as…

3 weeks ago