JavaScript Currying and Partial Application
Currying turns a function of several arguments into a chain of functions with one argument each. Each call in the chain fixes one argument and returns the next function.
One argument at a time
add takes one argument and returns a function. That function takes the second argument and returns the sum.
function add(a) {
return function (b) {
return a + b;
};
}
console.log(add(2)(3));A specialised function from a general one
Storing one step of the chain fixes the first argument. The stored function is a specialised version of multiply.
function multiply(a) {
return function (b) {
return a * b;
};
}
const double = multiply(2);
const triple = multiply(3);
console.log(double(7));
console.log(triple(7));Three arguments in a chain
A curried function can chain three steps or more. Each step returns the next function until the last step returns the result.
function sumThree(a) {
return function (b) {
return function (c) {
return a + b + c;
};
};
}
console.log(sumThree(1)(2)(3));Partial application with a stored step
withTax fixes the rate and returns a price function. The same rate applies to every price it sees.
function withTax(rate) {
return function (price) {
return price + price * rate;
};
}
const addVat = withTax(0.2);
console.log(addVat(100));
console.log(addVat(50));Example
function buildUrl(base) {
return function (path) {
return function (page) {
return base + "/" + path + "?page=" + page;
};
};
}
const shopUrl = buildUrl("https://shop.example");
console.log(shopUrl("books")(2));
console.log(shopUrl("toys")(1));Key points
- Currying: turning a function of several arguments into a chain of one-argument functions
- Partial application: fixing some arguments now and leaving the rest for later
- Each step in a curried chain returns a new function.
- The last step runs the work and returns the result.
- Use currying to build a specialised function from a general one.
In this example, buildUrl is a curried function with three steps. The first step fixes the base address. The second step fixes the path, and the last step adds the page number.
Note
A curried function needs one call per argument, so add(2)(3) is two calls.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
What does add(2) return when add is a curried function of two arguments?