Skip to main content
FREE Mock interview & resume review with Sumit. Free right now, no payment needed.Book a slot

Currying & Memoization — JavaScript interview guide

6 / 23Functions & ObjectsHigh priorityMedium 25 min

Currying & Memoization

Currying turns f(a, b, c) into f(a)(b)(c). Memoization caches results so the same input is not computed twice. Both rely on closures.

See it run

Press Play, or step with Next. Watch the highlighted line, the Call Stack and memory change together.

Memoization: the cache lives in a closure

Execution phaseStep 1/9
script.js
1function memoize(fn) {
2 const cache = {};
3 return (n) => {
4 if (n in cache) return cache[n];
5 return (cache[n] = fn(n));
6 };
7}
8
▶const square = memoize((n) => {
10 console.log("computing", n);
11 return n * n;
12});
13
14console.log(square(4));
15console.log(square(4));
Call Stack
last in, first out
Globalrunning
Memory / Scope
Global
squareƒ memoized
Closure (memoize)
fnƒ (n) => n*n
cache{}
Console

nothing printed yet

What happens:memoize returns a new function. Through a closure it keeps two things: the original fn and an empty cache object.

Tip: click the box and use ← → keys to step, space to play.

Explained simply

Currying

Useful for creating specialised functions from general ones.

const curry = (fn) =>
  function curried(...args) {
    return args.length >= fn.length
      ? fn(...args)
      : (...next) => curried(...args, ...next);
  };

const add = curry((a, b, c) => a + b + c);
add(1)(2)(3); // 6
add(1, 2)(3); // 6

Infinite currying: sum(1)(2)(3)()

A favourite interview twist: keep returning a function until called with no argument.

const sum = (a) => (b) => (b === undefined ? a : sum(a + b));
sum(1)(2)(3)(); // 6

Memoization

Store results in a cache inside a closure, keyed by the arguments.

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

Remember this

  • fn.length gives the number of declared parameters.
  • Memoize only pure functions.
  • React.memo and useMemo are memoization ideas too.

Interview questions

Where is currying useful in real code?

Creating pre-configured helpers, e.g. a logger(level)(message), event handlers with fixed ids, or partial application in functional utilities.

Practice

  1. Make sum(1)(2)(3) also work with sum(1, 2)(3)().
  2. Memoize a recursive Fibonacci and compare timings.

Keep learning