Function Currying
What is currying
In one sentence: the process of turning a function that takes several arguments into a function that takes one argument and returns a function that accepts the rest is called currying a function. It is commonly used for: cutting down code volume when bundling JS scripts and shrinking the bundled file size; and for interview questions.
An example of currying — the classic add
Suppose we have this function:
function add(a, b) {
return a + b
}To curry it, we can rewrite it into the following shape:
function addCurry(a) {
return function(b) {
return a + b
}
}That is function currying.
An example of currying — add over a fixed number of numbers
Suppose we have this function:
function add(a, b, c) {
return a + b + c
}To curry it, we can rewrite it into the following shape:
function addCurry(a) {
return function(b) {
return function(c) {
return a + b + c
}
}
}If you think that's too redundant, you can try the following rewrite:
let addArray = []
function addCurry(...args) {
addArray.push(...args)
if (addArray.length > 3) {
let result = addArray.splice(0, 3).reduce((a, b) => {
return a + b
})
addArray = []
return result
}
return addCurry
}An example of currying — add over a custom number of numbers
Suppose here we want a function that can add up a custom number of numbers; then we can rewrite the code from the previous question into the following shape:
function addInNumberOf(length) {
let addArray = []
return function addCurry(...args) {
addArray.push(...args)
if (addArray.length > length) {
let result = addArray.splice(0, length).reduce((a, b) => {
return a + b
})
addArray = []
return result
}
return addCurry
}
}This function is used like this:
let addThreeTimes = addInNumberOf(3);
console.log(addThreeTimes(1)(2)(3)); // prints 6In this example:
- The first call, addInNumberOf(3), returns a new function, which we assign to the variable addThreeTimes.
- By calling addThreeTimes(1)(2)(3) in succession we get the result 6.
- Because every call pushes the new argument into the array, once the array reaches length 3 it computes 1+2+3 and returns the result.
Important
This article was translated by Hermes Agent; the original text can be found at here. The translation is for reference only. Translation time: 2026-11-05
