Function Composition

Function Composition is the process of combining two or more functions to produce a new function. It's a fundamental concept in functional programming that enables building complex functionality from simple, reusable parts.

🎯 Understanding Composition

Mathematical Concept:
(f ∘ g)(x) = f(g(x))

            Where:
            ∘ is the composition operator
            g is applied first to x
            f is applied to the result of g(x)

The output of one function becomes the input of the next function.

Key Principles:
  • Associative: f ∘ (g ∘ h) = (f ∘ g) ∘ h
  • Not Commutative: f ∘ g ≠ g ∘ f (order matters)
  • Identity Function: f ∘ id = f = id ∘ f
  • Small Functions: Compose small, pure functions
  • Declarative: Focus on "what" not "how"
Compose (Right-to-Left)
compose(f, g, h)(x) = f(g(h(x)))

Traditional mathematical order

Pipe (Left-to-Right)
pipe(h, g, f)(x) = f(g(h(x)))

More readable for most developers

🔧 Examples

JavaScript Editor

JavaScript Editor

JavaScript Editor

JavaScript Editor

💪 Practice Exercise

JavaScript Editor
💡 Composition Tips:
  • Start with small, pure functions
  • Each function should do one thing well
  • Use descriptive names for composed functions
  • Test individual functions before composing
  • Consider using libraries like Ramda or lodash/fp

🏆 Composition Benefits

🧩
Modularity

Build complex systems from simple parts

♻️
Reusability

Small functions can be reused in different contexts

🧪
Testability

Easy to test small, pure functions

📖
Readability

Declarative code shows intent clearly

🔧
Maintainability

Easy to modify and extend

Performance

Can optimize individual functions

🎯
Abstraction

Hide complexity behind simple interfaces