Sub topic 11
Partial Application
This chapter assumes you know JavaScript closures, rest and spread syntax, and the curry helper from the previous chapter. You should also be comfortable running snippets in Node.js.
Partial application means fixing some of a function's arguments now and getting back a new function that takes the rest later. If send(host, path, body) always uses the same host, you can make a sendToApi(path, body) with the host already filled in. Nothing runs at that point. The new function just remembers the fixed values in a closure.
Partial Application vs. Currying
People often mix these two up, because both produce specialized functions. They are different operations.
| Technique | Input | Output | Calls needed |
|---|---|---|---|
| Currying | `f(a, b, c)` | `a => b => c => ...` | One per argument (or grouped) |
| Partial application | `f(a, b, c)` plus some args | `(b, c) => ...` | One more call with all remaining args |
| `Function.prototype.bind` | `f`, a `this` value, some args | Bound function | One more call |
A curried function is reshaped once and can then be partially applied at every step. Partial application works on an ordinary function and fixes arguments in a single step. You don't have to curry a function before you can partially apply it.
Built-in Partial Application with bind
JavaScript already ships one tool for this. bind takes a this value first, then any arguments to fix.
const multiply = (a, b) => a * b;
const double = multiply.bind(null, 2);
const triple = multiply.bind(null, 3);
console.log(double(21)); // 42
console.log(triple(5)); // 15
console.log(double.length); // 1 (2 declared params minus 1 bound arg)
console.log(double.name); // bound multiplybind keeps length accurate, which matters later. Its main drawback is the mandatory first argument. When the function doesn't use this, you have to pass null anyway. If you leave it out, your first real argument quietly becomes this and is never passed as a parameter.
Writing Your Own partial Helper
A hand-written helper takes only a few lines and reads more clearly than bind(null, ...).
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const partialRight = (fn, ...preset) => (...later) => fn(...later, ...preset);
const greet = (greeting, name, punctuation) => `${greeting}, ${name}${punctuation}`;
const hello = partial(greet, 'Hello');
console.log(hello('Ada', '!')); // Hello, Ada!
const shout = partialRight(greet, '!!!');
console.log(shout('Hey', 'Grace')); // Hey, Grace!!!
const helloAda = partial(greet, 'Hello', 'Ada');
console.log(helloAda('.')); // Hello, Ada.partial fixes arguments from the left. partialRight fixes them from the right, which helps when the value you want to fix sits last in the parameter list, such as an options object.
Placeholders for Middle Arguments
Sometimes the argument you want to fix sits in the middle. Libraries such as Lodash and Ramda handle this with a placeholder value. Here is a small version that uses a unique symbol:
const _ = Symbol('placeholder');
const partialWith = (fn, ...preset) => (...later) => {
let i = 0;
const args = preset.map((arg) => (arg === _ ? later[i++] : arg));
return fn(...args, ...later.slice(i));
};
const greet = (greeting, name, punctuation) => `${greeting}, ${name}${punctuation}`;
const toAda = partialWith(greet, _, 'Ada', '!');
console.log(toAda('Hello')); // Hello, Ada!
console.log(toAda('Bye')); // Bye, Ada!Each placeholder is filled in order from the later arguments. Any later arguments left over are appended at the end.
Designing Functions for Partial Application
Partial application only works well when the arguments you want to fix come first. Put configuration first and data last, and partial application, currying and composition all become easy.
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
// Config first, data last
const formatPrice = (currency, locale, amount) =>
new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount);
const usd = partial(formatPrice, 'USD', 'en-US');
const eur = partial(formatPrice, 'EUR', 'de-DE');
console.log([9.5, 120].map((n) => usd(n))); // [ '$9.50', '$120.00' ]
console.log(eur(1234.5)); // 1.234,50 €If you can't change a function's signature, for example a third-party API that takes data first, use partialRight or a placeholder, or wrap it in a small arrow function.
Common Errors and Gotchas
Extra Arguments from Callbacks
Array methods pass more than one argument to their callback. forEach and map call it with (value, index, array). A partially applied variadic function will take all three.
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const log = partial(console.log, '[app]');
['start', 'stop'].forEach(log);
// [app] start 0 [ 'start', 'stop' ]
// [app] stop 1 [ 'start', 'stop' ]
const unary = (fn) => (x) => fn(x);
['start', 'stop'].forEach(unary(log));
// [app] start
// [app] stopThis is the same bug as the well-known ['1', '2', '3'].map(parseInt), which returns [1, NaN, NaN]. Wrapping the callback in unary (or writing (x) => log(x)) passes only the first argument.
Lost Arity Breaks curry
A rest-parameter wrapper always reports length 0. The arity-based curry helper from the previous chapter depends on fn.length, so the two don't combine safely.
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const curry = (fn) => {
const curried = (...args) =>
args.length >= fn.length ? fn(...args) : (...more) => curried(...args, ...more);
return curried;
};
const add3 = (a, b, c) => a + b + c;
const viaPartial = partial(add3, 1);
console.log(viaPartial.length); // 0
console.log(curry(viaPartial)(2)); // NaN: called at once with (1, 2), c is undefined
const viaBind = add3.bind(null, 1);
console.log(viaBind.length); // 2
console.log(curry(viaBind)(2)(3)); // 6If arity matters, use bind or set length explicitly with Object.defineProperty(wrapper, 'length', { value: n }).
Losing this
The helper calls fn as a plain function, so methods lose their receiver. bind is the tool to use for methods.
'use strict';
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const account = {
fee: 2,
charge(amount) { return amount + this.fee; }
};
const chargeTen = account.charge.bind(account, 10);
console.log(chargeTen()); // 12
const broken = partial(account.charge, 10);
try {
broken();
} catch (e) {
console.log(e instanceof TypeError); // true: this is undefined
}Arrow functions ignore the this given to bind, but bind still fixes their arguments.
Fixed Arguments Are Evaluated Once
Preset arguments are evaluated when you create the partial function, not each time you call it.
const partial = (fn, ...preset) => (...later) => fn(...preset, ...later);
const stamp = (time, msg) => `${time}: ${msg}`;
const logNow = partial(stamp, Date.now());
// Every call reuses the same timestamp.
const settings = { retries: 1 };
const run = partial((opts, job) => `${job} x${opts.retries}`, settings);
settings.retries = 5;
console.log(run('sync')); // sync x5: the object was captured by referenceIf you need a fresh value on each call, pass a function and call it inside. If you need a stable snapshot, copy the object before fixing it, for example with { ...settings }. A frozen or immutable config avoids the second issue entirely.
When to Reach for Which Tool
- Use
bindfor methods that needthis, or when an accuratelengthmatters. - Use a
partialhelper for plain functions where readability matters most. - Use placeholders or
partialRightwhen you can't reorder the parameters. - Use an inline arrow,
(x) => f(a, x), for one-off cases. It's explicit, controls arity, and needs no helper.
Exercise
Given const fetchJson = (baseUrl, path, options) => ..., create apiGet that fixes baseUrl to "https://api.example.com" and options to { method: 'GET' }, leaving path open, using the partialWith placeholder helper.
Show answer
const apiGet = partialWith(fetchJson, 'https://api.example.com', _, { method: 'GET' }); Then call apiGet('/users'). The placeholder _ takes the first later argument, so path becomes '/users'.
Exercise
Why does ['10', '20'].map(partial(parseInt)) return [10, NaN], and how do you fix it?
Show answer
map passes (value, index, array), so parseInt receives the index as its radix. With radix 0 it parses '10' normally, but radix 1 is invalid, so '20' gives NaN. Fix it with ['10', '20'].map((s) => parseInt(s, 10)) or map(unary(partialRight(parseInt, 10))).
Exercise
You need a partially applied method that keeps its this and reports the correct length to a curry helper. Which tool do you choose and why?
Show answer
Use Function.prototype.bind, as in obj.method.bind(obj, firstArg). It fixes the receiver, and it sets length to the declared parameter count minus the bound arguments, so an arity-based curry still works.