Currying and Partial Application
Both turn a function of several arguments into something you can supply in stages, and they are not the same technique.
Partial application fixes some arguments and returns a function taking the rest. Currying converts a function of N arguments into N functions of one argument each. Both rely on closures, and both are asked about because they test whether you understand functions as values.
EXERCISE
1Fixing Some Arguments Now
Partial application is the one you will actually use, and you have already met it in Unit 2.
The idea:
function log(level, module, message) {
console.log(`[${level}] ${module}: ${message}`);
}
const logError = partial(log, "ERROR");
const logAuthError = partial(log, "ERROR", "auth");
logError("db", "connection lost"); // [ERROR] db: connection lost
logAuthError("token expired"); // [ERROR] auth: token expired
Each version fixes some arguments and leaves the rest. Nothing is recomputed; the original function is called with the fixed arguments in front of whatever arrives later.
The implementation is three lines:
function partial(fn, ...fixed) {
return function (...rest) {
return fn.apply(this, [...fixed, ...rest]);
};
}
That is bind from Unit 2 without the this half. In fact bind already does this:
const logError = log.bind(null, "ERROR");
Passing null as the receiver and then arguments is partial application, which is why Unit 2 said bind(null, ...) should read as "specialise this function" rather than as anything about this.
Notice what has not happened here. log was not modified, copied or wrapped in any logic. logError is a new function holding a reference to log and one captured string, and calling it calls the original. That is the whole of partial application, and it is why it costs essentially nothing to create a dozen specialised versions.
Why argument order suddenly matters:
// Badly ordered for partial application: the varying part is first
function fetchFrom(url, apiKey, timeout) { /* ... */ }
// Well ordered: stable configuration first, varying data last
function fetchFrom(apiKey, timeout, url) { /* ... */ }
const request = partial(fetchFrom, MY_KEY, 5000);
request("/users");
request("/posts");
Arguments are consumed from the left, so the ones you will fix belong at the front. Designing a function with this in mind costs nothing and makes it far more reusable.
And the everyday version people write without naming it:
// This is partial application, spelled with an arrow:
const request = (url) => fetchFrom(MY_KEY, 5000, url);
// Which is clearer than the helper for one or two cases,
// and worse when you need a dozen variations.
Recognising that an arrow capturing some arguments is the same technique is more useful than memorising a partial helper, because it is what you will see in real code.
EXERCISE
2Currying, and Why It Looks Strange
Currying is stricter than partial application, and the strictness is what makes it compose.
The definition:
// A function of three arguments:
function add(a, b, c) {
return a + b + c;
}
add(1, 2, 3); // 6
// Curried: three functions of one argument each
const curriedAdd = (a) => (b) => (c) => a + b + c;
curriedAdd(1)(2)(3); // 6
Each call takes exactly one argument and returns a function expecting the next. The chain of parentheses looks alien the first time and is simply three calls.
The closures are doing the work: the innermost function can see a, b and c because each one was captured by the function that received it.
A helper that curries an existing function:
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 add = curry((a, b, c) => a + b + c);
console.log(add(1)(2)(3)); // 6
console.log(add(1, 2)(3)); // 6
console.log(add(1)(2, 3)); // 6
console.log(add(1, 2, 3)); // 6
fn.length is the number of declared parameters, which is how the helper knows when it has enough. That is a real property of every function and worth remembering:
console.log(((a, b, c) => 0).length); // 3
console.log(((a, ...rest) => 0).length); // 1, rest does not count
console.log(((a, b = 2) => 0).length); // 1, defaults stop the count
Those last two are why an automatic curry cannot work on a function with rest or default parameters.
Where currying genuinely helps:
const prop = curry((key, obj) => obj[key]);
const getName = prop("name");
const users = [{ name: "Ada" }, { name: "Grace" }];
console.log(users.map(getName)); // [ 'Ada', 'Grace' ]
const filterBy = curry((predicate, list) => list.filter(predicate));
const onlyAdults = filterBy((u) => u.age >= 18);
Every curried function is already shaped to be passed to map, filter or a composition, because it takes its data last and returns a function until it has everything.
And the honest assessment:
// In a JavaScript codebase that is not committed to functional
// programming, currying is rare and partial application is common.
// It is asked about in interviews because it tests closures,
// rest and spread, fn.length and functions as values all at once.
Pro Tip: Learn the difference precisely, because the terms get used interchangeably and they are not the same. Partial application fixes some arguments and returns a function taking the rest. Currying converts one function of N arguments into N functions of exactly one. Every curried function can be partially applied; not every partially applied function is curried.
EXERCISE
3Where These Appear in Real Code
You have almost certainly used both techniques already, under other names.
Neither technique is exotic. They are everywhere, usually without the label.
Event handlers with a fixed first argument:
function handleAction(action, event) {
dispatch({ type: action, target: event.target });
}
saveButton.addEventListener("click", (e) => handleAction("save", e));
deleteButton.addEventListener("click", (e) => handleAction("delete", e));
// The same thing, named:
const onSave = partial(handleAction, "save");
const onDelete = partial(handleAction, "delete");
The arrow version is partial application written inline. Most codebases are full of it.
Configured clients:
function request(baseUrl, headers, path) {
return fetch(`${baseUrl}${path}`, { headers });
}
const api = partial(request, "https://api.example.com", { "X-Key": KEY });
await api("/users");
await api("/posts");
Every HTTP client library does some version of this: axios.create({ baseURL }) returns a function with the configuration already fixed.
Comparators for sort:
const by = (key) => (a, b) => (a[key] > b[key] ? 1 : -1);
users.sort(by("age"));
users.sort(by("name"));
by is curried, and the result slots straight into sort because it takes its data last.
Middleware, which is currying at scale:
const logger = (options) => (next) => (request) => {
if (options.verbose) console.log(request.url);
return next(request);
};
const withLogging = logger({ verbose: true });
Express, Redux and Koa all have this shape: configuration, then the next handler, then the request. Three nested arrows is a curried function of three arguments, and recognising that makes middleware far less mysterious the first time you meet it.
The thread running through all four examples is that the varying part comes last. A handler's event, a client's path, a comparator's two values, a middleware's request. That is not a coincidence: it is what makes partial application possible, and designing a function that way is a small decision with a large payoff.
And the one place to be careful:
// A new function on every render or every call
function Row({ item }) {
return <button onClick={partial(handleClick, item.id)} />;
}
Each call creates a new function, so anything comparing by identity, such as 's memoisation or removeEventListener, sees a change every time. That is the same point as creating a debounced function inside a handler: build it once, outside, where its identity is stable.
