Currying in JavaScript 🍛

Brian Wang
2 min readJun 7, 2021

--

Photo by Nadir sYzYgY on Unsplash

Recently, there was this problem I encountered and it made me realize there is this really important technique in JavaScript and other languages that I didn’t fully understand.

I believe a lot of you have seen functions like these:

const result = add(a, b, c) // or
const result = add(a)(b)(c) // or
const result = a => b => c => { return a + b + c }

This transformation is called currying and it translates a function from callable as f(a, b, c) into callable as f(a)(b)(c). This process does not call the function, it just transfers it. The resulting function is called curried function.

If we break f(a)(b)(c) down, it equals:

function curry(f) { // curry(f) does the currying transform   
return function(a) {
return function(b) {
return function(c) {
return f(a, b, c)
}
}
}
}
// example
function multiply(a, b, c) {
return a * b * c
}
let mathOperation = curry(multiply)console.log(mathOperation(2)(2)(2)) // result is 8

Now this all starts to make sense, but what is the actual use of this transformation? The beauty of it lies in the ability to make convenience functions with fixed arguments, in other words “partially applied function” or “partial” for short. For example:

// now we want mathOperation to at least multiply 2 no matter what
let double = mathOperation(2)
// use it
console.log(double(3)(4)) // equals 2 * (3 * 4)

The argument of mathOperation(2) is saved in the Lexical Environment and the returned result is saved in the variable double which is a wrapper function(b)or multiply(2, b, c) . The great thing about this is mathOperation is still callable as usual and we can also generate partial functions such as double .

One last example where we create a generic mathOperation that does different arithmetic operations:

mathOperation = (arg) => {
if (arg === '+') {
return (a, b) => { return (a + b) }
}
if (arg === '*') {
return (a, b) => { return (a * b) }
}
}
var multiple = mathOperation('*')if (multiple(3, 5) == 15) {
console.log('Successful multiply')
}
var add = mathOperation('+')if (add(2, 4) == 6) {
console.log('Successful addition')
}

I hope this article was helpful and you are now more confident with Curry functions either with the chained parentheses next to each other or the ES6 arrows.

--

--

Brian Wang
Brian Wang

Written by Brian Wang

Self Developer | Tech Junkie | Professional Nap Taker 🐨

No responses yet