JavaScript Interview Question #180
What is function composition?
Advanced JavaScript, Practical Problems & Senior Interview Scenarios Senior Advanced
Quick Interview Answer
Function composition combines smaller functions so the output of one becomes the input of another. It encourages small focused transformations that can be tested independently and assembled into more complex behavior.
Detailed Explanation
Function composition combines smaller functions so the output of one becomes the input of another. It encourages small focused transformations that can be tested independently and assembled into more complex behavior.
Composition is particularly useful for validation, formatting, data transformation, and reusable processing pipelines.
Code Example
const trim = value => value.trim();
const lower = value => value.toLowerCase();
const addPrefix = value => `user:${value}`;
const compose = (...functions) =>
value => functions.reduceRight(
(result, fn) => fn(result),
value
);
const normalize =
compose(addPrefix, lower, trim);
console.log(normalize(" ASIF "));
// user:asif