Contents

Functional programming in JavaScript: Currying

What is currying?

Currying is one of those concept that is easier to show than to define but let’s give it a try

In functional programming, currying is the process of spreading multiple arguments of a function across a sequence of nested functions.

Now that I attempted to give a definition let’s see what it actually means in practice.

The starting point for currying is a function that accepts multiple arguments.

Add function

Here is an add function that takes 3 arguments and sums them.

1
2
const add = (a, b, c) => a + b + c
add(2, 2, 6) // 10

Nothing too special so far but now let’s try creating a curried version of it:

1
2
const add = (a) => (b) => (c) => a + b + c
add(2)(2)(6) // 10

As you can see we moved each argument to a dedicated function and what we get is a structure where each function returns another function that you are supposed to call passing the next argument until you reach the end.

Why would I need it?

Currying is particularly helpful when you have to call a function with the same arguments over and over again.

Example

If we see that we call the add function passing the same a and b many times, I could assign the first 2 functions of the curried version to a variable and then call it passing only the third parameter.

1
2
3
4
5
const add4 = add(2)(2); // Function that sums 2 and 2

add4(6) // 10
add4(10) // 14
...

How to create curried functions

Of course we could turn each function into a curried version in the same way we did it earlier but if wouldn’t be very efficient.

What we want is a function that handles if for us without having to worry about the implementation the function we want to “currify”.

Although there are several libraries that provides such functionality, see Lodash curry, here is how you can do it yourself.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
function curry(fn) {
    return function curried(...args) {
        if (args.length >= fn.length) {
            return fn.apply(this, args);
        } else {
            return function(...args2) {
                return curried.apply(this, args.concat(args2));
            }
        }
    };
}

The curry function creates a recursive curried function that, when the passed args length is equal or greater than the original function (fn) args, it calls fn passing the args using fn.apply(this, args). Otherwise, instead of calling fn, another wrapper is returned, that will re-apply the curried function passing the previous arguments along with the new ones.

Now, we can pass the original add to our new curry function and use the curried result.

1
2
3
const add = (a, b, c) => a + b + c
const curriedAdd = curry(add)
console.log(curriedAdd(4)(2)(2); // 8

In this tutorial, we have examined the currying transformation process in JavaScript.