JavaScript ES6 curry functions with practical examples

Martin Novák
Jan 22, 2018 · 4 min read
Ms. Curie meets Mr. Curry

There is a lot of mathematical and computer science theory behind currying in functional programming and I encourage you to read more on Wikipedia. Interesting fact: Currying is named after a mathematician Haskell Curry, not the food.

Basic example

Most basic example, that you will find everywhere, is this:

const sum = x => y => x + y;// returns the number 3
sum (2)(1);
// returns a function y => 2 + y
sum (2);

Note that produces the same result that we would get, if we had defined it as , which we would call as
.

If seeing more than one arrow gives you a trouble, just realize that you are simply returning everything that is behind the first arrow. In this case it’s returning another function as its return value, because JavaScript has first class functions. Also this approach works, because the nested returned function has access to the scope of its parent function and so conviniently the gets the from its parent.

First class functions

Anyone reading about currying should probably understand the concept of first class functions in JavaScript. In short, in functional programming JavaScript has first class functions because it supports functions as arguments and return values.

const someFunction = () => console.log ('Hello World!');const firstClass1 = functionAsArgument => functionAsArgument ();
firstClass1(someFunction); // Hello World! is printed out
const firstClass2 = () => someFunction;
firstClass1 (firstClass2()); // Hello World! is printed out

If you have been using JQuery, then you have probably already used the awesomeness of first-class functions here:

$ ('button').click (function () {
console.log ('I was clicked!');
});

There you are telling JQuery to run your function when a button is clicked, by using your function as an argument for JQuery click function. If you are interested in understanding other basic terms of functional programming in JavaScript, read my post: 6 fundamental terms in functional JavaScript.

Practical example: curry as a partial application

This is an example of partially applied function versus curry function, both doing the same thing using JQuery “on” function:

const partiallyAppliedOnClick = handler => $ ('button').on ('click', handler);
const curryOn = handler => event => $ ('button').on (event, handler);
const curryOnClick = handler => curryOn (handler) ('click');

Curry functions are neat when used to carry containers of reusable code. Basically you take a function with multiple arguments and you know that one of those arguments will have specific value but the other is undecided. Therefor by using curry, as a fancy partial application, you can create a new function which will allow you to deal only with the undecided arguments without repeating your code.

Practical example: curry for functional composition

Functional composition is a concept deserving its own post. The problem that we are trying to solve by currying is the fact that JavaScript is full of object oriented approaches which can be challenging to use with functional code, especially if you want to be a purist (or a hipster) about it.

Currying

Currying is the process of taking a function with multiple arguments and turning it into a sequence of functions each with only a single argument.

const notCurry = (x, y, z) => x + y + z; // a regular functionconst curry = x => y => z => x + y + z; // a curry function

This is an example of currying applied on a familiar JavaScript method and generating new functions using it:

// JavaScript substring: str.substr(start[, length])const curriedSubstring = start => length => str
=> str.substr(start, length);
const getSubstring = (start, length, str)
=> curriedSubstring (start) (length) (str);
const getFirstCharacters = (length, str) =>
curriedSubstring (0) (length) (str);
const getFirstCharacter = str => curriedSubstring (0) (1) (str);

Functional composition

In functional composition you have a sequence of functions applied all on the same single argument as . This would be your example:

// Object oriented approach
const getUglyFirstCharacterAsLower = str
=> str.substr (0, 1).toLowerCase ();
// Functional approach
const curriedSubstring = start => length => str
=> str.substr(start, length);
const curriedLowerCase = str => str.toLowerCase ();
const getComposedFirstCharacterAsLower = str
=> curriedLowerCase (curriedSubstring (0) (1) (str));

It is also very popular to use a compose function to compose your functions::

const compose = (...fns) =>
fns.reduce((f, g) => (...args) => f(g(...args)));

Using the above-defined functions and you can then use compose to do this:

const getNewComposedFirstCharacterAsLower
= compose (curriedLowerCase, curriedSubstring (0) (1));
if (getComposedFirstCharacterAsLower ('Martin') ===
getNewComposedFirstCharacterAsLower ('Martin') {
console.log ('These two provide equal results.');
}

Practical use in an example project

I have used curried functions when I was developing my NPM package conditional-expression. You can read more about it in my post: How to replace switch and ternaries in functional JavaScript.

You can see the actual code here: https://github.com/MartinGentleman/conditional-expression/blob/master/src/index.js

Using currying led to a better code. I chose syntax:

match(something).equals(something).then(result).else(default);

instead of:

match(something).equals(something, result).else(default);

Thanks to that, I have created the function, which later made it easier for me to create different logic based on inner branching needs and support for nesting.

Conclusion

If you have your heart set on imperative object-oriented programming, you can shamelessly ignore currying in JavaScript and carry on being happy with finally having official class syntax. If you are looking for more information, try this post: 8 steps to turn imperative JavaScript class to a functional declarative code.

However, if you have at least a bit of a mathematician with a strike of a logician in you, give a try to functional programming with declarative expressions using currying. You will love it.

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

Martin Novák

Written by

Frontend Weekly

It's really hard to keep up with all the front-end development news out there. Let us help you. We hand-pick interesting articles related to front-end development. You can also subscribe to our weekly newsletter at http://frontendweekly.co

More From Medium

More from Frontend Weekly

More from Frontend Weekly

More from Frontend Weekly

Understanding `static` in React

4.3K

More from Frontend Weekly

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade