Sitemap

Understanding Function Composition in JavaScript

2 min readFeb 22, 2025

--

Press enter or click to view image in full size
Function Composition in JavaScript

What is Function Composition?

Function composition is a technique used to combine multiple functions into a single function. It works by passing the output of one function as the input to another, allowing for cleaner and more modular code.

Let’s first understand this concept with an example that does not use function composition.

Example Without Function Composition

function add(x) {
return x + 2;
}
function mul(x) {
return x * 2;
}
const result = add(mul(4)); // Output: 10
console.log(result);

Here, we first call mul(4), which returns 8, and then pass this value to add(8), resulting in 10.

Using Function Composition

We can achieve the same result in a more modular and reusable way using function composition.

function add(x) {
return x + 2;
}
function mul(x) {
return x * 2;
}
function compose(f, g) {
return function(x) {
return f(g(x));
};
}
const composite = compose(add, mul)(4);
console.log(composite); // Output: 10

How Function Composition Works

  1. We define a higher-order function compose(), which takes two functions, f and g, as arguments and returns a new function.
  2. The returned function applies g(x) first, then passes its result to f(x).
  3. When we call compose(add, mul)(4), it stores add and mul in memory as closures and passes 4 to the composed function.
  4. mul(4) executes first, returning 8, which is then passed to add(8), returning 10.

Key Concept: Right-to-Left Execution

In function composition, execution happens from right to left. In compose(add, mul), mul executes first, and then add processes the result.

Why Use Function Composition?

✅ Modular Code — Instead of writing nested function calls like add(mul(4)), we can simply use compose(add, mul)(4), making the code cleaner.

Get Saurav sharma’s stories in your inbox

Join Medium for free to get updates from this writer.

✅ Readability & Reusability — The composed function is easier to understand and can be reused across different parts of the application.

✅ Scalability — Function composition is especially useful in enterprise-level applications, where maintaining clean and scalable code is crucial.

Conclusion

Function composition is a powerful concept in JavaScript that improves code clarity, reusability, and scalability. By structuring functions in a modular way, we can build more maintainable and readable code.

I hope this article helps you understand function composition in JavaScript. Happy coding! 🚀

--

--