Course contentsShow
← JavaScript
Lesson 1778 of 2,72337. Functional Programming PatternsFree lesson

Manual Composition: Nested Calls

Understand how nested function calls like f(g(h(x))) represent composition and why they can be hard to read.

Manual Composition: Nested Calls

You'll learn how nested function calls represent composition and why they quickly become difficult to read.


The Core Idea

When you compose functions manually, you nest them: the output of one function becomes the input of the next. In JavaScript, this looks like f(g(h(x))). While this is technically correct composition, it introduces a readability problem—especially as the chain grows longer.

The execution order is inside-out: h(x) runs first, its result feeds into g, and that result feeds into f. This right-to-left reading order contradicts how we naturally read code (left-to-right), making it harder to follow the data flow.

Example: Processing User Input

const trim = str => str.trim();
const lowercase = str => str.toLowerCase();
const addExclamation = str => str + '!';

const input = '  Hello World  ';

// Manual composition via nested calls
const result = addExclamation(lowercase(trim(input)));
console.log(result); // "hello world!"

This works, but notice:

  • You must read from right-to-left to understand the order: trim, then lowercase, then add exclamation
  • Each new function adds another layer of parentheses
  • With five or six functions, this becomes a pyramid of closing parentheses

The Readability Challenge

// Hard to track what's happening
const finalValue = funcA(funcB(funcC(funcD(funcE(value)))));
// Which function runs first? Count parentheses to find out!

Key Takeaway: Manual composition through nested calls (f(g(h(x)))) works but reads inside-out, becoming increasingly difficult to understand as the chain grows—this motivates cleaner composition patterns.