DEV Community

Discussion on: Currying in JS 🤠

Collapse
 
aminnairi profile image
Amin • Edited

Hi there and thanks for your article!

In my opinion, this article deserves a little bit more explanations, especially the usefulness of using curried functions.

If I start from your example.

const isDivisible = divider => number => !(number % divider);

console.log(isDivisible(2)(40)); // true
console.log(isDivisible(2)(33)); // false
console.log(isDivisible(3)(40)); // false
console.log(isDivisible(3)(33)); // true
Enter fullscreen mode Exit fullscreen mode

Even though you have successfully curried your function, we can see that the 2 & 3 parameters could have been reused. Now if I take this example.

const isDivisible = divider => number => !(number % divider);

console.log(isDivisible(2)(40)); // true
console.log(isDivisible(2)(33)); // false
console.log(isDivisible(2)(29)); // false
console.log(isDivisible(2)(26)); // true
Enter fullscreen mode Exit fullscreen mode

We can see that I'm repeating the 2 a lot. What is great about curried functions is that they can be used to compose higher order functions (a higher order function is a function that either takes a function as parameter or returns a new one), and so helping us reuse some parameters that are commons accross function calls.

const isDivisible = divider => number => !(number % divider);
const isDivisibleByTwo = isDivisible(2);

console.log(isDivisibleByTwo(40)); // true
console.log(isDivisibleByTwo(33)); // false
console.log(isDivisibleByTwo(26)); // true
console.log(isDivisibleByTwo(39)); // false
Enter fullscreen mode Exit fullscreen mode

And this is, in my opinion, what makes currying so powerful. Composing functions helps you decrease the needs for repeating common parts of your application.

Collapse
 
lbayliss profile image
Luke Bayliss

This is what I was expecting to read!

Collapse
 
wakeupmh profile image
Marcos Henrique

Thanks for the explanation,I tried to introduce the characteristic of flexibility, although this approach that you said was the most common as to the power of currying.