Currying in JavaScript

Home » Blog » Software » Currying in JavaScript

A reference to logician Haskell Curry, currying is a technique for converting a function that takes multiple arguments into a chain of abstract functions that each take a single argument (see Currying).

Besides its significance for studying functions in the context of theoretical computer science and its relevance to lambda calculus both in the context of mathematics and linguistics, currying has very practical applications in functional programming.

In a way, it’s one possible approach for following the inversion of control design principle and implementing dependency injection within a functional programming context. Of course, these concepts usually apply to object-oriented architectures. However, that doesn’t mean those aren’t useful in terms of functional programming. In a nutshell, currying allows us to define an abstract function, pass that function down the call chain, and only define its dependencies once those become relevant and applicable. Using this technique we can delegate the definition of behaviour that is extraneous to the function we’re implementing to the call site of that function.

The Modern JavaScript Tutorial includes a short and comprehensible article on currying and how to use that – admittedly fairly theoretical – concept in an actual application. The example they use is defining a logging function with the current date set as a dependency. This enables the developer who uses that function to not have to worry about instantiating the Date class.

Another – slightly more complex – example can be seen in this GitHub Gist, where I delegated the addition of a specific precondition header to an error handling function that retries an original HTTP request with an HTTP header serving as a confirmation message.

About the author: Bjoern
Independent IT consultant, entrepreneur
One comment

    Leave a Comment