Memoization — JS Technical Interview Questions & Answers

Caching expensive function results by input.

Memoization

  • Memoization (js) is a JS topic. In plain words you use it for a short Memoization js example in a script in the browser. Don’t start with a slogan — start with that picture.
  • Smallest example: the smallest Memoization js example you can type. Type it, run it, and say what you see. If you can do that from memory, you know Memoization (js).
  • From the example next to this theory: Caching expensive function results by input.
  • Trap: only saying “Memoization js” with no example. Fix that before you talk about advanced JS.
  • Viva: what is Memoization (js)? Then show the smallest Memoization js example you can type. Then name the trap.

Technical Interview Tip: What is Memoization (js)? Show this: the smallest Memoization js example you can type. Trap: only saying “Memoization js” with no example.

Code Examples for Memoization

Memoization — working example

const double = (n) => n * 2;
const inc = (n) => n + 1;
const compose = (f, g) => (x) => f(g(x));
console.log(compose(double, inc)(3)); // double(inc(3)) = 8

function* ids() {
  yield 1;
  yield 2;
}
console.log([...ids()]);

function memoize(fn) {
  const cache = new Map();
  return (x) => {
    if (cache.has(x)) return cache.get(x);
    const y = fn(x);
    cache.set(x, y);
    return y;
  };
}
const slowSquare = memoize((n) => n * n);
console.log(slowSquare(9), slowSquare(9));

console.log("A");
setTimeout(() => console.log("C"), 0);
Promise.resolve().then(() => console.log("B"));
// Order: A, B, C

Memoization — compose pipelines; generators pause with yield; memoize caches; async work is scheduled via the event loop.

How to Explain Memoization to an Interviewer

What is Memoization (js)?

Used for a short Memoization js example a script in the browser Not just the heading

Give one small example of Memoization (js).

the smallest Memoization js example you can type Caching expensive function results by input

What mistake do beginners make with Memoization (js)?

only saying “Memoization js” with no example Show the fix

Where do you use Memoization (js)?

a script in the browser a short Memoization js example