JavaScript Function Composition

Function composition is the process of combining two or more functions to produce a new function. It’s a key principle in functional programming that helps write cleaner, modular, and reusable code.

Instead of chaining actions manually, composition lets you build complex operations from simple, focused functions.



Understanding Function Composition (Made Simple)

Function composition means connecting simple functions so they run one after another. The output from one function becomes the input for the next.

It’s like a process: Step 1 ➡️ Step 2 ➡️ Step 3. Each function does one small task, and they work together to solve a bigger problem.

javascript
function double(x) {
    return x * 2;
}

function square(x) {
    return x * x;
}

function composed(x) {
    return square(double(x));
}

console.log(composed(3)); // 36

double(3) gives 6
square(6) gives 36

Why Use Function Composition?

  • Makes your code cleaner and easier to understand
  • Breaks big tasks into small, reusable functions
  • Avoids repeating the same logic

Making a Compose Function

Let’s create our own compose function! This function will take two other functions and combine them into one. The result of the second function will be passed into the first function automatically.

This way, you don’t have to call one function inside another manually every time.

javascript
// Step 1: Define the compose function
function compose(f, g) {
    return function(x) {
        // g runs first, then f uses its result
        return f(g(x));
    };
}

// Step 2: Create two simple functions
function double(x) {
    return x * 2;
}

function square(x) {
    return x * x;
}

// Step 3: Use compose to combine them
const result = compose(square, double)(4);

// Step 4: Print the result
console.log(result); // 64

Here's what's happening step by step:

  • double(4) runs first and returns 8.
  • Then square(8) runs and returns 64.
  • So compose(square, double)(4) is the same as square(double(4)).

This is function composition — combining two functions to work together as one.


Example 1: Formatting a User's Name

Let’s say we want to take a user's name, clean it up, and format it nicely. We'll remove extra spaces, convert it to lowercase, and then capitalize the first letter.

javascript
function trim(str) {
    return str.trim();
}

function toLower(str) {
    return str.toLowerCase();
}

function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function compose(f1, f2, f3) {
    return function(x) {
        return f1(f2(f3(x)));
    };
}

const formatName = compose(capitalizeFirst, toLower, trim);

console.log(formatName("   eMMA   ")); // "Emma"

How It Works:

  • trim removes the spaces from both ends → "eMMA"
  • toLower turns it into "emma"
  • capitalizeFirst makes it "Emma"
  • The functions are composed right to left: first trim, then toLower, then capitalizeFirst.

Output

Emma

Example 2: Composing Math Functions

In this example, we’ll combine math functions to process a number. We'll double the number, then add 3, and finally square the result.

javascript
function double(x) {
    return x * 2;
}

function addThree(x) {
    return x + 3;
}

function square(x) {
    return x * x;
}

function compose(f1, f2, f3) {
    return function(x) {
        return f1(f2(f3(x)));
    };
}

const processNumber = compose(square, addThree, double);

console.log(processNumber(2)); // 49

How It Works:

  • double(2)4
  • addThree(4)7
  • square(7)49
  • The functions are composed right to left: first double, then addThree, and finally square.

Output

49

Frequently Asked Questions

What is function composition in JavaScript?

Function composition in JavaScript is the process of combining two or more functions to produce a new function. The output of one function becomes the input of the next.


Why should I use function composition?

Function composition helps you write cleaner, reusable, and modular code. It breaks down complex logic into smaller, manageable functions.


How does the compose function work?

The compose function takes multiple functions and returns a new function. When called, it applies those functions from right to left, passing the result of each function into the next.


What is the difference between compose and pipe?

The difference lies in the order of execution. compose applies functions from right to left, while pipe applies them from left to right. Both are used to build function chains.


Can I compose more than two functions?

Yes, you can compose as many functions as you want. A generic compose function uses reduceRight() to handle any number of functions.



What's Next?

Up next, you'll learn about JavaScript Strict Mode. It’s a special way to write JavaScript that helps you avoid common mistakes. Strict mode makes your code cleaner, safer, and easier to debug by turning silent errors into visible ones. It's a great tool for beginners who want to build good coding habits from the start.