JavaScript ES6 curry functions with practical examples
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…