bene : studio is a global consultancy, helping startups, enterprises and HealthTech companies to have better product

Currying in JavaScript ES6

currying in JS

Pardon the interruption, we have an important message!

We are looking to expand our team with talented developers. Check out our open positions and apply.

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)

Is There Uncurrying?

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

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

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)

Real World Currying Examples

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

JavaScript Bind

Function.prototype.bind() does partial application actually.

// first param is thisArg which is irrelevant nowincrement = 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.

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.

What do you think?

Have some comments or want to ask some questions? Share them with us via e-mail to partner@benestudio.co and we can set up a talk with our engineers.

Looking for a new job or a partner to develop your next project? Check out our open positions and our services to see what we do.

currying in JS

Let bene : studio enhance
your digital product!