Sub topic 13
Partial Application and Currying
This chapter assumes you already know what a closure is and that closures capture variables rather than copies of their values. It also uses rest parameters (...args), spread syntax, and Function.prototype.apply. You will build two related techniques on top of closures. Partial application fixes some of a function's arguments now and supplies the rest later. Currying turns a function of several arguments into a chain of functions that take them one or a few at a time.
Partial Application: Fixing Arguments Ahead of Time
Partial application means calling a function with only some of its arguments and getting back a new function that waits for the remaining ones. The new function is a closure. It remembers the arguments you already gave it.
The simplest version is written by hand:
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
console.log(double(5)); // 10
console.log(multiply(3)(4)); // 12When multiply(2) runs, it creates a lexical environment where a is 2. The inner function closes over that environment. multiply has already returned by the time you call double(5), but a is still reachable through the closure. Each call to multiply creates a fresh environment, so double and multiply(3) never share an a.
A Reusable `partial` Helper
Writing a nested function for every case gets repetitive. A generic helper takes any function plus some preset arguments:
function partial(fn, ...preset) {
return function (...later) {
return fn(...preset, ...later);
};
}
const log = (level, message) => `[${level}] ${message}`;
const warn = partial(log, 'WARN');
const error = partial(log, 'ERROR');
console.log(warn('Disk almost full')); // [WARN] Disk almost full
console.log(error('Disk full')); // [ERROR] Disk fullThe returned function closes over two things: fn and the preset array. The later arguments arrive when the new function is called, and the closure joins the two lists in order.
`bind` Is Built-in Partial Application
JavaScript already ships a partial application tool. Function.prototype.bind takes a this value followed by any number of preset arguments:
function volume(length, width, height) {
return length * width * height;
}
const baseTen = volume.bind(null, 10);
console.log(baseTen(2, 3)); // 60
const tenByTwo = volume.bind(null, 10, 2);
console.log(tenByTwo(5)); // 100Currying: One Argument at a Time
Currying transforms a function f(a, b, c) into f(a)(b)(c). Each call takes one argument (or, in the looser style most JavaScript libraries use, one or more) and returns either the next function in the chain or the final result.
A hand-written curried function is just nested closures:
const addThree = (a) => (b) => (c) => a + b + c;
console.log(addThree(1)(2)(3)); // 6
const addOne = addThree(1);
const addOneAndTwo = addOne(2);
console.log(addOneAndTwo(10)); // 13Every intermediate function is a closure holding the arguments collected so far. addOne holds a = 1. addOneAndTwo holds b = 2 and can reach a through the scope chain.
A Generic `curry` Helper
A generic curry uses the function's length property, which reports how many parameters it declares. The helper keeps collecting arguments until it has enough, then calls the original:
function curry(fn) {
return function curried(...args) {
if (args.length >= fn.length) {
return fn.apply(this, args);
}
return function (...more) {
return curried.apply(this, [...args, ...more]);
};
};
}
const sum3 = curry((a, b, c) => a + b + c);
console.log(sum3(1)(2)(3)); // 6
console.log(sum3(1, 2)(3)); // 6
console.log(sum3(1)(2, 3)); // 6
console.log(sum3(1, 2, 3)); // 6Trace sum3(1)(2)(3):
curried(1)has one argument, which is fewer thanfn.length(3). It returns a closure capturingargs = [1].- Calling that closure with
2runscurried(1, 2). Two is still fewer than three, so it returns a new closure capturing[1, 2]. - Calling that closure with
3runscurried(1, 2, 3). Now the count matches, andfnruns.
Each step builds a new array instead of pushing onto a shared one. That matters: you can branch from any intermediate function and the branches stay independent.
const startWithOne = sum3(1);
const a = startWithOne(10)(100); // 111
const b = startWithOne(20)(200); // 221
console.log(a, b);Partial Application Versus Currying
The two ideas overlap, and people often use the words loosely. The table shows how they differ.
| Aspect | Partial application | Currying |
|---|---|---|
| What it produces | One new function with some arguments fixed | A chain of functions, one per argument (or group) |
| Number of calls to get a result | Usually two: preset, then the rest | As many as it takes to reach the full count |
| Needs to know arity | No | Yes, usually through `fn.length` |
| Built-in support | `bind` | None; you write a helper or use a library |
| Typical use | Specializing one function, such as a logger with a fixed level | Composing small functions in a functional style |
A curried function can do partial application on demand: sum3(1) is a partially applied function. A partially applied function is not curried, because it does not keep returning functions.
Common Errors and Gotchas
`fn.length` Lies with Defaults and Rest Parameters
length counts only the parameters before the first default value or rest parameter. A generic curry then fires too early.
function greet(greeting, name = 'friend') {
return `${greeting}, ${name}!`;
}
console.log(greet.length); // 1
const curriedGreet = curry(greet);
console.log(curriedGreet('Hi')); // 'Hi, friend!' (called right away)A function declared as (...nums) => ... has a length of 0, so curry calls it with no arguments at all. To curry such functions, have the helper accept an explicit arity, for example curry(fn, 2).
Extra Arguments from Callbacks
Array methods pass more arguments than you might expect. map calls its callback with (value, index, array). A loose curried function accepts all of them:
const clamp = curry((min, max, n) => Math.min(Math.max(n, min), max));
console.log([5, 50, -3].map(clamp(0, 10))); // [5, 10, 0]
console.log([5, 50, -3].map(clamp(0))); // [0, 1, 2] — wrongIn the second line, clamp(0) receives (5, 0, array). It treats 5 as max and the index 0 as n. Each element becomes the upper bound, and the index gets clamped. Wrap the call so only the value reaches the function: .map((n) => clamp(0, 10, n)).
Preset Objects Are Captured by Reference
The closure holds the preset value itself. If that value is an object or array, later changes to it show up in every call:
const join = (items, extra) => [...items, extra].join(', ');
const tags = ['js'];
const withTags = partial(join, tags);
console.log(withTags('web')); // js, web
tags.push('closures');
console.log(withTags('web')); // js, closures, webIf you want a frozen snapshot, copy the value when you create the partial: partial(join, [...tags]).
Argument Order Decides Usefulness
You can only preset arguments from the left (with partial, bind, and curry alike). Put the arguments that change least often first and the data that changes most often last. A function written formatPrice(currency, amount) specializes nicely into formatUSD. The same function written formatPrice(amount, currency) does not.
Losing `this`
A plain partial helper that calls fn(...) drops this. The curry helper above uses fn.apply(this, args) so methods keep working when the curried function is attached to an object. Use the same approach whenever the wrapped function relies on this.
Exercise
Given const sub = curry((a, b) => a - b);, what do sub(10)(3) and [1, 2, 3].map(sub(10)) return, and why?
Show answer
sub(10)(3) returns 7. The map call returns [9, 8, 7]. map passes (value, index, array), so each call receives [10, value, index, array]. That is at least 2 arguments, so fn runs as fn(10, value) and the extra arguments are ignored. Because the arity is 2, the extra arguments do no harm here, unlike the three-parameter clamp example.
Exercise
Write a partialRight(fn, ...preset) helper that fixes arguments on the right side, so that partialRight((a, b) => a / b, 2)(10) returns 5.
Show answer
function partialRight(fn, ...preset) { return function (...later) { return fn.apply(this, [...later, ...preset]); }; } The closure holds preset and puts it after the arguments supplied later.
Exercise
Why does curry((...nums) => nums.length) return 0 as soon as you call it with no arguments, and how would you fix the helper?
Show answer
A rest parameter gives the function a length of 0, so args.length >= fn.length is true right away and fn runs immediately. Fix it by letting curry take an explicit arity, such as function curry(fn, arity = fn.length), and compare against arity instead of fn.length.