Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

Memoization Advanced in JavaScript

Cache square results in JavaScript with a closure and Map.has, so a cached zero is reused too. This cheap calculation teaches the pattern, not a measured speedup.

AdvancedAdvanced JavaScriptExample 5 of 12

Run this example once in a fresh browser console. The console shows the printed results.

memoization-advanced.js
1function memoizeSquare() {
2 const cache = new Map();
3 return function (number) {
4 if (!Number.isFinite(number)) throw new Error('Use a finite number');
5 if (cache.has(number)) {
6 console.log('Cache hit:', number);
7 return cache.get(number);
8 }
9 const result = number * number;
10 console.log('Calculated:', number);
11 cache.set(number, result);
12 return result;
13 };
14}
15const square = memoizeSquare();
16console.log(square(4));
17console.log(square(4));
18console.log(square(0));
19console.log(square(0));

Sample Output

Calculated: 4, then 16

The first call computes the square and saves it.

Cache hit: 0, then 0

The repeated zero input is present in the Map even though the stored result is falsy.

In this one

  • Cache results by numeric input
  • Distinguish a missing entry from zero
  • Keep a cache local to a function
  • Recognize stale and unbounded caches

How it works

  1. 1

    Create a private Map when memoizeSquare runs.

  2. 2

    Reject non-finite input.

  3. 3

    Use has to check whether the number already has a result.

  4. 4

    Compute and save only when the input is new.

  5. 5

    Call 4 and 0 twice to see one calculation and one cache hit for each.

Edge cases

Zero result

A truthiness check would treat cached zero as missing.

Use cache.has(number) separately from cache.get(number).

Growing cache

Every new number leaves another Map entry.

For large workloads, choose a maximum size or an expiry rule. A cache without a limit can consume increasing memory.

What's going on

Memoization saves a function result so the same input can reuse it later. The saved results are often called a cache, which is a store of values kept to avoid repeating work. This example squares numbers and reports whether it calculated or reused each result.

The Map belongs to the returned function through a closure. A closure is a function that remembers variables from where it was created. cache.has checks whether an input is present. It must not rely on the truth of cache.get, because zero is a valid result but acts like false in a condition.

The second call for 4 reuses 16, and the second call for 0 reuses 0. Squaring is cheap, so this example teaches the pattern rather than claiming a speed improvement. Memoization makes sense for repeatable calculations: the same input must mean the same result. Results that depend on time, changing data, or side effects can become stale. A long-running app also needs a cache size or expiry policy.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Which check correctly finds a cached zero?

Pick an answer to check it.

Question 2

What kind of calculation is safest to cache?

Pick an answer to check it.

Questions people ask

Why not use JSON.stringify on every input?

This lesson only accepts numbers, so a direct Map key is clearer. General serialization has restrictions, including object ordering and unsupported values.

Will this make squaring faster?

Not necessarily. Cache lookup and storage may cost more than one multiplication. It is a pattern demonstration.

Can I memoize a current-time function?

Not safely as a permanent result for the same input. Time changes, so a cached value can become wrong.