Function Composition — JS Technical Interview Questions & Answers

Combining small functions into a pipeline.

Function Composition

  • Function Composition (js) is a JS topic. In plain words you use it for add(a, b) in a checkout total. Don’t start with a slogan — start with that picture.
  • Smallest example: function add / const add = () =>. Type it, run it, and say what you see. If you can do that from memory, you know Function Composition (js).
  • From the example next to this theory: Combining small functions into a pipeline.
  • Trap: this surprise in arrow vs function. Fix that before you talk about advanced JS.
  • Viva: what is Function Composition (js)? Then show function add / const add = () =>. Then name the trap.

Technical Interview Tip: What is Function Composition (js)? Show this: function add / const add = () =>. Trap: this surprise in arrow vs function.

Code Examples for Function Composition

Function Composition — 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

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

How to Explain Function Composition to an Interviewer

What is Function Composition (js)?

Used for add(a, b) a checkout total Not just the heading

Give one small example of Function Composition (js).

function add / const add = () => Combining small functions into a pipeline

What mistake do beginners make with Function Composition (js)?

this surprise in arrow vs function Show the fix

Where do you use Function Composition (js)?

a checkout total add(a, b)