Course contentsShow
← JavaScript
Lesson 485 of 2,72312. Higher-Order FunctionsFree lesson

When Composition Helps vs Hurts

Recognizing scenarios where composition improves code versus when direct calls are clearer.

When Composition Helps vs Hurts

You'll learn: when to reach for function composition and when simpler approaches make your code clearer.

The Core Idea

Function composition isn't always the answer. While chaining transformations like pipe or compose can elegantly express data flow, there are times when a straightforward function call or simple variable is far more readable. The key is recognizing whether composition clarifies intent or just adds ceremony.

When Composition Helps

Composition shines when you're performing multiple sequential transformations on data:

const formatUserName = pipe(
  trim,
  toLowerCase,
  removeSpecialChars
);

// Clear pipeline of transformations
const clean = formatUserName(userInput);

This reads like a recipe: trim, then lowercase, then clean. Each step is obvious.

When Composition Hurts

If you only have one or two operations, composition adds unnecessary abstraction:

// Over-engineered
const double = pipe(x => x * 2);
const result = double(5);

// Just do this
const result = 5 * 2;

Similarly, if the logic involves branching or conditions, composition fights against you. Don't force imperative logic into a functional straitjacket.

The Litmus Test

Ask yourself: "Does this composition make the flow clearer, or am I just showing off?" If someone else (or future-you) needs to mentally "unwrap" the composition to understand what's happening, you've gone too far.

Key Takeaway: Use composition when you have clear, sequential transformations that tell a story together. For simple operations or complex branching logic, direct function calls keep your code honest and maintainable.