DEV Community

loading...
Cover image for JavaScript Currying

JavaScript Currying

toddster79 profile image Todd Carlson ・1 min read

This week, as I was learning about functional programming with JavaScript, I came across the concept of currying. As per usual I got to learn a cool new programming term that I had never heard before. This weeks' fun new word was "arity." If you hear someone refer to the "arity" of a function, they are talking about the number of arguments that the function requires. With this in mind, currying a function means to convert a function of X "arity" into X functions of "arity" 1. Let's look at an example to get a better understanding of what this means.

const normalFunction = (a, b) => {
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Here we have an example of an un-curried function with an "arity" of 2, since it takes in two arguments a, and b.

const curriedFunction = a => b => a + b;

curriedFunction(2)(4)

// returns 6
Enter fullscreen mode Exit fullscreen mode

If, for some reason, you are unable to supply all of the arguments for a function at one time, this could come in handy. You could save each function call into a variable, which would hold the value of the returned function which could then take the next argument when it becomes available.

let funcB = curriedFunction(1);

console.log(funcB(2));

// Returns 3
Enter fullscreen mode Exit fullscreen mode

And there you have it, a short and sweet introduction to JavaScript currying. I encourage you all to explore this topic in more depth, since I have heard it is a fairly common question to encounter during technical interviews.

Discussion

pic
Editor guide