Ask any question about JavaScript here... and get an instant response.
How can I compose multiple functions to transform data in a single pipeline in JavaScript?
Asked on Dec 13, 2025
Answer
Function composition in JavaScript allows you to combine multiple functions into a single function that processes data in sequence. This is often used to create a pipeline of transformations.
<!-- BEGIN COPY / PASTE -->
const compose = (...functions) => input =>
functions.reduceRight((acc, fn) => fn(acc), input);
const add = x => x + 1;
const multiply = x => x * 2;
const addThenMultiply = compose(multiply, add);
console.log(addThenMultiply(5)); // Output: 12
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "compose" function takes multiple functions as arguments and returns a new function.
- "reduceRight" is used to apply each function from right to left, passing the result of each function to the next.
- "addThenMultiply" is a composed function that first adds 1 to the input, then multiplies the result by 2.
- This pattern is useful for creating reusable and readable data transformation pipelines.
Recommended Links:
