Javascript/Memoization
Javascript / Topic

Memoization

Learn how memoization improves performance by caching expensive function results and reusing them for identical inputs.

Difficulty

Advanced

Read time

18 min

Format

Concept + Code

Focus

Interview ready
Concepts
Memoization
Performance
Caching

01 / Foundation

Understand the concept

Memoization is an optimization technique where function results are cached so repeated calls with the same input return the cached value instead of recalculating.

Memoization is widely used in JavaScript, React, dynamic programming, and performance optimization.

02 / Implementation

Memoization Example

memoization.js
function memoize(fn) {
  const cache = {};

  return function (num) {
    if (cache[num]) {
      console.log("Returning from cache");
      return cache[num];
    }

    console.log("Calculating...");

    cache[num] = fn(num);

    return cache[num];
  };
}

const add200 = memoize((num) => num + 200);

console.log(add200(20));
console.log(add200(20));
console.log(add200(30));

04 / Interview

Test your understanding