Currying in JavaScript ES6

Currying can give you a deeper understanding to JavaScript. Let’s see how it can be done with arrow functions!

define tripe function by a curried multiply function

What is Currying?

There is a way to reduce functions of more than one argument to functions of one argument, a way called currying after Haskell B. Curry. [1]

Currying is a process to reduce functions of more than one argument to functions of one argument with the help of lambda calculus.

f(n, m) --> f'(n)(m)
curry example

Is There Uncurrying?

Oh, yes. Uncurrying is the inverse operation of currying.

f(n)(m) --> f'(n, m)
uncurry example

What About Partial Application?

Partial application means that you pre-applied a function partially regarding to any of its arguments.

f(n, m) --> f'(m)
papply example

Real World Currying Examples

You must be wondering how this theoretical toolset can be revealed in daily life.

JavaScript Bind

Function.prototype.bind() does currying actually.

// first param is thisArg which is irrelevant now
increment = add.bind(undefined, 1)
increment(4) === 5

React and Redux

The simplest use case of the react-redux connect() function is a purely curried one.

export default connect(mapStateToProps)(TodoApp)

Event Handling

Event handler can be reused for multiple fields.

const handleChange = (fieldName) => (event) => {
saveField(fieldName, event.target.value)
}
<input type="text" onChange={handleChange('email')} ... />

Rendering HTML

Render function can be reused to render similar HTML tags.

rendering HTML using curried functions

Curry as Higher Order Function

We can define curry, uncurry and papply as higher order functions as follows. Arrow notation is right associative so we can omit brackets.

Properties

Curry and uncurry are inverses. Let’s check that.

Conclusion

Curry as a term has been living for almost 40 years now and is an essential transformation in lambda calculus.

JavaScript is being used more as a functional language nowadays especially with native promises and arrow functions. To master the language you should have some knowledge in the field of lambda calculus and functional programming. Going beyond Gang of Four this is a good way to build higher and better software constructions.

References

[1] The Kleene Symposium, page 86. North Holland Publishing Company,
Amsterdam, 1980.