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

Unary Functions in Composition

Discover why composed functions work best as unary (single-argument) and how to adapt multi-argument functions.

Unary Functions in Composition

You'll learn why composed functions expect single arguments and how to safely feed multi-argument functions through a composition pipeline.

Why Unary Matters

When you compose functions, each function's output becomes the next function's input. This works smoothly when every function accepts exactly one argument (unary):

const addOne = x => x + 1;
const double = x => x * 2;
const square = x => x * x;

const compose = (...fns) => x => fns.reduceRight((v, fn) => fn(v), x);

const transform = compose(square, double, addOne);
transform(3); // (3 + 1) * 2 → 8, then 8² → 64

The Multi-Argument Problem

JavaScript's built-in functions often accept multiple arguments. When composed, this causes issues:

const pipe = (...fns) => x => fns.reduce((v, fn) => fn(v), x);

// parseInt accepts (string, radix) — dangerous in composition!
const parse = pipe(
  x => x.trim(),
  parseInt  // BUG: will receive unexpected arguments from reduce!
);

parse(" 42 "); // May fail unpredictably

The Unary Wrapper Solution

Wrap multi-argument functions to accept only the first argument:

const unary = fn => arg => fn(arg);

const parse = pipe(
  x => x.trim(),
  unary(parseInt)  // Now safe: only passes the string
);

parse(" 42 "); // 42 ✓

Think of composition as a single-file assembly line: each station can only handle one item at a time. Unary ensures each function receives exactly what it expects, nothing more.

Key Takeaway:
Composed functions should be unary (single-argument); wrap multi-argument functions with a unary helper to prevent unexpected behavior when values flow through the pipeline.