DEV Community

Cover image for Functional programming basics part 3: Currying
ysael pepin
ysael pepin

Posted on

Functional programming basics part 3: Currying

So what is this thing people are calling currying?

Currying is simply the action of converting a function that take multiple arguments into one that can support the ability to return a new function if the argument it got is not the last one.

If it is the last argument, it will execute.

Let's say I have a simple function:

const add = (x, y) => x + y;

Enter fullscreen mode Exit fullscreen mode

If I try to call it with only one argument, it fails...

const add = (x, y) => x + y;

add(1) // undefined 
// (x is now 1 but y is undefined, so 1 + undefined = undefined)

Enter fullscreen mode Exit fullscreen mode

Fortunately, modern JavaScript give us the ability to curry very easily via arrow functions.

Here is the same function curried:

const add = x => y => x + y;

add(1) // function add() 
/* (this newly returned function as encapsulated 
the value of 1 and will look like this --> y => 1 + y ) */

Enter fullscreen mode Exit fullscreen mode

The nice thing about this is that now, we can call it with only one argument witch will return a new function that will expect one last argument y.

We could alternatively put that new returned function in a variable and start using it:

const add = x => y => x + y;

const add1 = add(1);


console.log(add1(1)) // 2
Enter fullscreen mode Exit fullscreen mode

Hope that helps you understand what currying is :)

Top comments (0)