Currying & Partial Application

Turning a multi-argument function into a chain of single-argument functions -- and pre-filling arguments to build specialised tools.

Syntaxconst f = a => b => c => a + b + c; const partial = f.bind(null, a);

Currying transforms f(a, b, c) into f(a)(b)(c) -- a chain of functions each taking one argument and returning the next. Partial application is the looser cousin: fix some arguments now, supply the rest later.

const add = (a) => (b) => a + b;
const add5 = add(5);   // partially applied
add5(3); // 8

Why bother

  • Build specialised functions from general ones -- const double = multiply(2).
  • Fit functions to point-free pipelines and array methods without wrapper lambdas.
  • Configure once, reuse everywhere -- a logger pre-bound to a level, a fetcher pre-bound to a base URL.

Closures make it work: each returned function remembers the arguments captured so far.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Create a curried tax-rate function that is pre-configured with a region's rate and reused across a billing module.
  • Build a partially applied logger with a fixed log level so each component gets its own labelled log function.
  • Use currying to compose a data validation pipeline where each rule is a single-argument predicate.

More examples

Basic curried function

Curries a two-argument multiply into two single-argument functions; triple is multiply pre-loaded with 3.

Example · js
const multiply = a => b => a * b;
const triple = multiply(3);
console.log(triple(5));  // 15
console.log(triple(10)); // 30

Curried logger with fixed label

Creates specialised loggers by partially applying a label, reusing the inner function across modules.

Example · js
const createLogger = label => msg => console.log(`[${label}] ${msg}`);
const dbLog = createLogger("DB");
const authLog = createLogger("AUTH");
dbLog("Connected");    // [DB] Connected
authLog("User login"); // [AUTH] User login

Generic curry utility

A general curry utility accumulates arguments until the original function's arity is satisfied.

Example · js
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) return fn(...args);
    return (...more) => curried(...args, ...more);
  };
}
const add = curry((a, b, c) => a + b + c);
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(3)); // 6

Discussion

  • Be the first to comment on this lesson.
Currying & Partial Application — JavaScript | SoundsCode