What Is Currying In JavaScript

JavaScript

20/05/2021


I like to describe currying as nested functions that can be sequentially called whenever you like to. You may in fact have already encountered some so far. This is what they look like:

JAVASCRIPT
someFunction('some')('string')('parameters')

Currying is a concept that can be applied not only to JavaScript, but any programming language in general.

Nested functions

Any function that takes in 2 or more parameters can be recreated as a curried 🍛 function. Take this simple addition function.

JAVASCRIPT
function add(a, b) {
return a + b
}
add(3, 2) // 5

To transform it into a curried function, apply the following changes:

JAVASCRIPT
function add(a) {
return function(b) {
return a + b
}
}
add(3)(2) // 5

You'll notice that a nested function is called by appending parentheses (with or without a parameter) onto the outer function call, e.g. someFunction()(). Naturally, you'll call and pass down any parameters to the nested functions in the order that they are defined.

Call it whenever you like

Remember how I said that a curried function "can be sequentially called whenever you like"? This is where they really shine! ✨

You should always keep in mind that a curried function will return another function until you call the most inner nested one. Let's continue with our previous example.

JAVASCRIPT
const nestedFunction = add(3)
console.log(nestedFunction) // function add(b)

If we call only the outer layer of our add function, it returns the nested function we defined earlier. Of course, you have to store the function somewhere, like nestedFunction in our example, or else you won't be able to call it afterwards.

Now... you could theoretically take a break, drink some coffee ☕️ and complete the curried function 15 minutes later and still receive the same output as before.

JAVASCRIPT
nestedFunction(2) // 5

And this is why one would use a curried function. Not so you can go on a break, 😆 but because you don't need all the parameters upfront to call a function.

You might have the 1st parameter ready, but it might take some time (and processing) until your 2nd, or 3rd parameter is available.


WRITTEN BY

Code and stuff