Function composition is a technique where you combine two or more functions to produce a new function. The output of one function becomes the input of the next. This leads to cleaner, reusable, and readable code.

💡 Core Idea
If you have functions f and g, composing them as f(g(x)) means you first apply g to x, then apply f to the result.
How Function Composition Works
- Call the innermost function first.
- Pass its result to the next function.
- Continue until all functions execute.
- Return the final output.
| Function | Description |
|---|---|
double(x) | Multiplies x by 2 |
increment(x) | Adds 1 to x |
📌 Deep Dive: Compose increment and double
const double = x => x * 2;
const increment = x => x + 1;
// Compose functions manually
const incrementThenDouble = x => double(increment(x));
console.log(incrementThenDouble(3)); // Output: 8
// Explanation: increment(3) => 4, then double(4) => 8
Here, incrementThenDouble is a composed function that combines two operations in sequence.
Utility: Writing a Compose Function
To generalize composition, you can write a helper function that composes multiple functions:
📌 Deep Dive: Implementing a compose Utility
const compose = (f, g) => x => f(g(x));
const double = x => x * 2;
const increment = x => x + 1;
const incrementThenDouble = compose(double, increment);
console.log(incrementThenDouble(5)); // Output: 12
// increment(5) => 6, double(6) => 12
💡 Remember
The order of composition matters: compose(f, g) applies g first, then f.
Benefits of Using Function Composition
- Modularity: Build complex logic from simple functions.
- Readability: Clear flow of data transformations.
- Reusability: Functions stay pure and focused.
⚠️ Be Careful with Side Effects
Function composition works best with pure functions (no side effects). Side effects can cause unpredictable results when composing.
Summary
- Function composition chains functions so output flows through each.
- Compose manually or with helper functions.
- Order of functions affects the result.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
In function composition compose(f, g), which function runs first?
Question 2 of 2
Which kind of functions are best suited for composition?
Loading results...