What is Function Composition?
You'll learn what function composition means and how it combines multiple functions into a powerful workflow.
The Core Idea
Function composition is the process of combining two or more functions so that the output of one function becomes the input of the next. You're essentially creating a pipeline where data flows through a series of transformations.
Think of it like an assembly line: raw material enters the first station, gets transformed, then moves to the next station for another transformation, and so on until you get the final product.
How It Works
Instead of calling functions separately and storing intermediate results:
const numbers = [1, 2, 3];
const doubled = numbers.map(x => x * 2);
const incremented = doubled.map(x => x + 1);
You can compose them by chaining operations where each function's output feeds directly into the next:
const numbers = [1, 2, 3];
const result = numbers
.map(x => x * 2)
.map(x => x + 1);
// [3, 5, 7]
The output from the first map becomes the input for the second map — that's composition in action!
A Real-World Analogy
Imagine a coffee shop workflow:
- Grind beans → produces ground coffee
- Brew coffee → takes ground coffee, produces hot coffee
- Add milk → takes hot coffee, produces latte
Each step depends on the previous step's output. That's function composition.
Why It Matters
Composition lets you build complex operations from simple, reusable functions. You've already seen this with chaining array methods like filter().map() — you're composing behaviors to transform data step by step.
Key Takeaway: Function composition combines functions where each function's output becomes the next function's input, creating a data transformation pipeline.