How to Compose Functions in JavaScript: Syntax and Examples
To compose functions in JavaScript, you create a new function that passes the output of one function as the input to the next using
function composition. This is often done by defining a compose function that chains multiple functions together, running them from right to left.Syntax
The compose function takes multiple functions as arguments and returns a new function. When called, this new function passes its input through each function from right to left, feeding the output of one as the input to the next.
- ...fns: Rest parameter to accept any number of functions.
- reduceRight: Runs functions from right to left.
- acc: Accumulator holding the current value passed through functions.
- fn: Current function applied to the accumulator.
javascript
const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);Example
This example shows how to compose two simple functions: one that doubles a number and another that adds three. The composed function applies addThree first, then double.
javascript
const double = x => x * 2; const addThree = x => x + 3; const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x); const doubleAfterAddThree = compose(double, addThree); console.log(doubleAfterAddThree(5));
Output
16
Common Pitfalls
One common mistake is composing functions in the wrong order, which changes the result. Remember that compose(f, g) means f(g(x)), so g runs first.
Another pitfall is not returning values from functions, which breaks the chain.
javascript
const f = x => x + 1; const g = x => x * 2; // Wrong order: g runs after f, not before const wrongCompose = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x); console.log(wrongCompose(f, g)(5)); // Outputs 12 (f(g(5)) expected 11) // Correct order using reduceRight const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x); console.log(compose(f, g)(5)); // Outputs 11 (f(g(5)))
Output
12
11
Quick Reference
Remember these tips when composing functions:
- Use
reduceRightto apply functions right to left. - Ensure each function returns a value.
- Compose functions to build reusable, clean code.
- Test composed functions with simple inputs first.
Key Takeaways
Function composition chains functions so output of one is input to the next, running right to left.
Use a
compose helper with reduceRight to build composed functions.Order matters:
compose(f, g) means f(g(x)), so g runs first.Always return values from each function to keep the chain working.
Composed functions help write cleaner and more reusable code.