How Does JavaScript’s curry() Actually Work?
Published in
7 min readDec 12, 2017
Lately I’ve been high on functional programming, courtesy of Eric Elliott’s exceptional “Composing Software” series–a must-read if you write JavaScript. At one point he mentioned currying, a tool that allows you to “partially apply” a function, meaning you don’t have to specify its arguments all at once.
So if you have
greet = (greeting, first, last) => `${greeting}, ${first} ${last}`
greet('Hello', 'John', 'Doe') // Hello, John Doe
Curry that and you get
curriedGreet = curry(greet)curriedGreet('Hello')('John')('Doe') // Hello, John Doe
curriedGreet('Hello', 'John')('Doe') // Hello, John Doe
As you fill up a curried function’s parameters, it returns functions that expect the remaining parameters.
A little more in-depth:
// greet requires 3 params: (greeting, first, last)// these all return a function looking for (first, last)
curriedGreet('Hello')
curriedGreet('Hello')()
curriedGreet()('Hello')()()// these all return a function looking for (last)
curriedGreet('Hello')('John')
curriedGreet('Hello', 'John')
curriedGreet('Hello')()('John')()// these return a greeting, since all 3 params were honored
curriedGreet('Hello')('John')('Doe')
curriedGreet('Hello', 'John', 'Doe')
curriedGreet('Hello', 'John')()()('Doe')