DEV Community

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

Posted on

5 1

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 :)

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay