Currying and Currying

Jeff Okawa
3 min readMar 9, 2018

--

In today’s TL;DR series, we’ll talk about JavaScript currying. Click here to know more about the TL;DR series.

This is not the technical definition, but currying is method of constructing a function that invokes another function with some of its arguments already bound to a value.

Supposed you have a function that takes two arguments, but you know for a particular context, you want to “permanently” set the value of one of the arguments for future inovations. Currying helps solve this issue:

output> 10

But currying is more than just functions returning functions. What we achieve with currying is the ability of passing an argument to a function one at a time instead of all at once — essentially redefining a multi-argument function into a series of single argument ones.

Each argument is its own parameter.

Which also allows us to do things like:

Introducing a Currier

That nested function structure can get pretty nasty so if you are doing a lot of currying, it’s better to use a currier function. There are third-party libraries that provide such functions, but you can also build your own:

When you call the currier function, you provide the function (target) you want to “curry” and the arguments to bind:

When the curried function is executed, the closure being returned invokes the target function with the arguments you initially supplied to create the curried function concatenated with the arguments you supplied when invoking the curried function. Read the code snippet above carefully to understand what’s going on. The curried function can then be invoked like:

output> a,b,x,z

Alternatives: function.prototype.bind()

Something you might have noticed was the call() invocation — which leads us to a hint that currying can also be achieved by using the bind() function.

output> a,b,c,d

Does it matter which to use?

  • Currying is more pure to functional programming (if that’s your thing)
  • The bind() function requires the context, which you can pass null if not required for your curried function (though some people find this syntactically ugly).

In the end…

There are times where curried functions offer a cleaner solutions to bind(), but many cases can be handled with bind alone. Currying just offers you another tool in your JavaScript arsenal, but the choice to use it is purely situational.

I love to hear any feedback or if there was something something I missed. Leave a comment below!

If you liked this story, please leave a clap!

--

--

Jeff Okawa

I like writing about digital solutions and social media. My Twitter is: @gepphkat