Interview Q&A / JavaScript

IntermediateQuick answerCoding1 min readUpdated 3 Oct 2026

Write a memoize function that caches the results of a pure function.

SHORT ANSWER

Wrap the function and store results in a Map keyed by its arguments. If the key exists, return the cached value; otherwise compute, store and return. It only works safely for pure functions.

Explain it simply

Memoizing is like a tea stall owner remembering your usual order. The first time he asks and makes it; every later time he skips the question and serves straight away.

The cache has to live between calls, so it sits in a closure. The key must identify the arguments. For simple cases JSON.stringify(args) works; for single primitive arguments the argument itself can be the key.

It is only safe for pure functions: same input must always give the same output, with no side effects.

Line by line

js
function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const value = fn.apply(this, args);
    cache.set(key, value);
    return value;
  };
}

let calls = 0;
const square = memoize((n) => { calls++; return n * n; });

console.log(square(9));  // Output: 81
console.log(square(9));  // Output: 81
console.log(calls);      // Output: 1

What to say in the interview

"I wrap the function with a closure holding a Map. The arguments are serialised into a key; a hit returns the stored value, a miss computes and stores it. It trades memory for speed, only suits pure functions, and the cache can grow without bound unless limited."

Complexity

Time O(1) average per cached lookup (plus key serialisation), otherwise the cost of fn. Space O(n) for n distinct argument sets.

Common mistakes

  • Memoizing a function that reads the clock or random numbers.
  • Using JSON.stringify keys with functions or undefined arguments, which serialise badly.

#javascript#closures#coding

Related questions

Practise more JavaScript questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open JavaScript quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.