Composition vs Chaining
You'll learn when to use function composition versus method chaining, and understand the trade-offs between these two functional patterns.
Understanding the Two Patterns
Both function composition and method chaining let you build pipelines of operations, but they work differently:
- Method chaining calls methods on objects, each returning a transformed version:
value.method1().method2().method3() - Function composition combines independent functions that pass results through:
compose(fn3, fn2, fn1)(value)
Think of chaining as a conveyor belt built into the object itself—each station (method) knows about the next. Composition is like connecting separate machines with pipes—each function is independent and reusable.
When to Use Each Pattern
Use method chaining when:
- Working with built-in APIs (arrays, strings, promises)
- Operations are tightly coupled to a specific data type
- You want readable, left-to-right flow (especially with libraries like Lodash chains)
const result = [1, 2, 3, 4, 5]
.filter(x => x > 2)
.map(x => x * 2)
.reduce((sum, x) => sum + x, 0);
Use composition when:
- Building reusable, independent functions
- Working with pure functions you can combine in different ways
- You need maximum flexibility and testability
const filterBig = arr => arr.filter(x => x > 2);
const double = arr => arr.map(x => x * 2);
const sum = arr => arr.reduce((sum, x) => sum + x, 0);
const result = sum(double(filterBig([1, 2, 3, 4, 5])));
The Key Difference
Chaining is convenient but locks you into a specific object type. Composition creates portable building blocks that work anywhere.
Key Takeaway: Method chaining is great for built-in APIs and quick transforms, while function composition shines when building reusable, testable function libraries that you can mix and match.