Currying & Partial Application
Turning a multi-argument function into a chain of single-argument functions -- and pre-filling arguments to build specialised tools.
Syntax
const 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); // 8Why 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
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.
const multiply = a => b => a * b;
const triple = multiply(3);
console.log(triple(5)); // 15
console.log(triple(10)); // 30Curried logger with fixed label
Creates specialised loggers by partially applying a label, reusing the inner function across modules.
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 loginGeneric curry utility
A general curry utility accumulates arguments until the original function's arity is satisfied.
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