Reading history

JavaScript Currying and Function Composition

5 min read 0 views

Learn currying, partial application with bind, and building function pipelines with pipe and compose in JavaScript.

In JavaScript, functions are values: you can pass them in, return them and store them. Two ideas from functional programming build on this. Currying turns a function of several arguments into a chain of one-argument functions, so you can fill in some arguments now and the rest later. Composition joins small functions into a pipeline, where each output feeds the next input. Together they let you build complex behaviour from tiny, easy-to-test pieces.

In this lesson you will learn

  • What currying is and how to write curried arrow functions
  • Creating specialised functions such as withVat15
  • A general curry helper and partial application with bind
  • Building pipelines with pipe and compose
  • Debugging a pipeline with a tap step

You should know higher-order functions and closures.

Currying

// A normal function takes all its arguments at once
function addVat(rate, price) { return price + price * rate; }
console.log(addVat(0.15, 200));

// A curried function takes one argument and returns a function for the next
const addVatCurried = rate => price => price + price * rate;
const withVat15 = addVatCurried(0.15);   // remember the rate
const withVat5  = addVatCurried(0.05);
console.log(withVat15(200), withVat15(1000), withVat5(200));

// Curried helpers work neatly with map and filter
const multiply = a => b => a * b;
const isAbove = min => n => n > min;
const prices = [80, 150, 420, 95];
console.log(prices.map(multiply(2)));
console.log(prices.filter(isAbove(100)));

// A general curry helper: call with one argument at a time, or several
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn(...args);
    return (...more) => curried(...args, ...more);
  };
}
const volume = curry((l, w, h) => l * w * h);
console.log(volume(2)(3)(4), volume(2, 3)(4), volume(2, 3, 4));

// Partial application with bind fixes the first arguments
const greet = (greeting, name) => `${greeting}, ${name}!`;
const salam = greet.bind(null, "Assalamu alaikum");
console.log(salam("Nadia"));

Output

230
230 1150 210
[ 160, 300, 840, 190 ]
[ 150, 420 ]
24 24 24
Assalamu alaikum, Nadia!
  • rate => price => ... is a function that returns a function. Calling addVatCurried(0.15) gives back a new function that remembers the rate through a closure.
  • That lets you make specialised functions: withVat15 and withVat5 are both built from one general function.
  • Curried helpers slot neatly into map and filter: prices.filter(isAbove(100)) reads almost like English.
  • The curry helper converts a normal function. It checks fn.length, the number of parameters, and keeps collecting arguments until it has enough. You can pass them one at a time or several together.
  • bind does partial application: it fixes the first arguments and returns a new function that takes the rest. The first argument to bind sets this; null is fine when this is not used.

Composition: pipe and compose

// Small single-purpose functions
const trim = s => s.trim();
const lower = s => s.toLowerCase();
const dashes = s => s.replace(/\s+/g, "-");
const noSymbols = s => s.replace(/[^a-z0-9-]/g, "");

// Nesting calls reads inside-out, which is hard to follow
console.log(noSymbols(dashes(lower(trim("  Monsoon in Sylhet!  ")))));

// pipe runs functions left to right; compose runs them right to left
const pipe = (...fns) => x => fns.reduce((value, fn) => fn(value), x);
const compose = (...fns) => x => fns.reduceRight((value, fn) => fn(value), x);

const slugify = pipe(trim, lower, dashes, noSymbols);
console.log(slugify("  Monsoon in Sylhet!  "));
console.log(slugify("Learn JavaScript   Fast"));

const slugify2 = compose(noSymbols, dashes, lower, trim);   // same steps, listed in reverse
console.log(slugify2("Hello World 2026"));

// A tap step lets you peek at the value in the middle of a pipe
const tap = label => x => { console.log(`  [${label}]`, JSON.stringify(x)); return x; };
const priceAfterDiscount = pipe(
  p => p * 0.9, tap("after 10% off"),
  p => p * 1.15, tap("after 15% VAT"),
  Math.round
);
console.log("Final:", priceAfterDiscount(1000));

Output

monsoon-in-sylhet
monsoon-in-sylhet
learn-javascript-fast
hello-world-2026
  [after 10% off] 900
  [after 15% VAT] 1035
Final: 1035
  • Each step does one small job: trim spaces, make lowercase, swap spaces for dashes, remove symbols.
  • Nested calls such as noSymbols(dashes(lower(trim(s)))) must be read from the inside out.
  • pipe(trim, lower, dashes, noSymbols) lists the same steps in the order they run. It uses reduce to pass the value through each function in turn.
  • compose does the same but runs right to left, matching the order of nested calls. Most people find pipe easier to read.
  • The result, slugify, is a new reusable function. It turns titles into URL slugs like the ones on this site.
  • tap logs the value and passes it on unchanged, so you can look inside a pipeline without breaking it.
TermMeaningExample
CurryingOne argument per calladd(2)(3)
Partial applicationFix some arguments nowgreet.bind(null, "Hi")
pipeRun functions left to rightpipe(f, g)(x) is g(f(x))
composeRun functions right to leftcompose(f, g)(x) is f(g(x))

Common Mistakes

  1. Calling a curried function all at once: addVatCurried(0.15, 200) ignores 200 and returns a function. Write addVatCurried(0.15)(200), or use the curry helper.
  2. Using the curry helper with default or rest parameters. These are not counted in fn.length, so the helper may call the function too early.
  3. Mixing up pipe and compose order, which runs the steps backwards.
  4. Pipeline steps that need two arguments. Each step receives one value, so curry the extra arguments first.

Practice Exercises

Exercise 1. Write a curried between(min)(max)(n) that returns true when n is in the range, then use it to keep marks from 40 to 79.

Show answer
const between = min => max => n => n >= min && n <= max;
const marks = [35, 42, 80, 67, 79];
console.log(marks.filter(between(40)(79)));   // [42, 67, 79]

Exercise 2. Use pipe to build initials, which turns "nadia islam" into "NI".

Show answer
const initials = pipe(
  s => s.split(" "),
  words => words.map(w => w[0]),
  letters => letters.join(""),
  s => s.toUpperCase()
);
console.log(initials("nadia islam"));   // "NI"

Frequently Asked Questions

Does JavaScript have a built-in pipe operator?

Not yet. A pipe operator (|>) has been proposed for JavaScript, but it is not part of the language. Until then, a small pipe helper or a library such as Ramda or lodash/fp does the job.

Do I need to curry everything?

No. Currying is useful when you often reuse a function with the same first arguments, or when building pipelines. For one-off calls, a normal function with several parameters is clearer.

Summary

  • Currying splits a function into a chain of one-argument functions, using closures to remember earlier arguments.
  • Specialised functions like withVat15 are made by supplying the first arguments early.
  • pipe and compose join small functions into a pipeline.
  • Small, single-purpose steps are easy to test, reuse and debug with tap.

Next: JavaScript Proxy and Reflect.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *