JavaScript ES6 curry functions with practical examples

Martin Novak
Frontend Weekly
Published in
5 min readJan 22, 2018

--

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 sum (2)(1); produces the same result that we would get, if we had defined it as const sum = (x,y) => x + y;, which we would call as
sum (2, 1);.

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 y => x + y gets the x 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

--

--

Martin Novak
Frontend Weekly

Martin is a product manager at work, a software developer in his free time, and an entrepreneur at heart.