DEV Community

Cover image for What is Currying in JavaScript and How to Use It
Danities Ichaba
Danities Ichaba

Posted on

What is Currying in JavaScript and How to Use It

Currying is a functional programming technique that allows you to create new functions by partially applying a function's arguments. It's a way of breaking down a function with multiple arguments into a series of functions that each take only one argument. Currying can make your code more modular, reusable, and easier to understand.

In JavaScript, currying is done by returning a new function from an existing function, with some arguments already applied. Here's an example:

function add(x) {
  return function(y) {
    return x + y;
  }
}

const add2 = add(2);
console.log(add2(3)); // 5
console.log(add2(4)); // 6

Enter fullscreen mode Exit fullscreen mode

In this example, the add function takes one argument x and returns a new function that takes one argument y and returns the sum of x and y. We then use add(2) to create a new function add2 that adds 2 to any number passed to it.

Currying can be especially useful when you have a function with many arguments that you need to reuse with different values for some of those arguments. By currying the function, you can create new functions that already have some of the arguments applied, and then use them as building blocks to create more complex functions.

Here's another example:

function multiply(x, y) {
  return x * y;
}

const double = multiply.bind(null, 2);
console.log(double(3)); // 6
console.log(double(4)); // 8

Enter fullscreen mode Exit fullscreen mode

In this example, we use the built-in bind method to create a new function double that multiplies its argument by 2. The first argument to bind is the this value, which we set to null because we don't need it in this case. The second argument is the value to bind to the first parameter of the multiply function, which is 2.

Currying can also be achieved using arrow functions:

const add = x => y => x + y;
const add2 = add(2);
console.log(add2(3)); // 5
console.log(add2(4)); // 6

Enter fullscreen mode Exit fullscreen mode

In this example, we define the add function as an arrow function that takes one argument x and returns another arrow function that takes one argument y and returns the sum of x and y. We then use add(2) to create a new function add2 that adds 2 to any number passed to it.

Currying in JavaScript has several practical applications that can help improve code readability, maintainability, and reusability.

Here are some practical use cases of currying:

  1. Reusable utility functions: Currying can help create reusable utility functions that can be easily customized for specific use cases. Currying allows you to create a function that returns another function with a partially applied argument. In this case, we have a curried add function that takes two arguments, a and b. When you call add with a single argument, it returns a new function that takes the second argument b and adds it to the initially provided a. Here's the example with more explanation:
const add = a => b => a + b;

// Create a new function 'add5' by calling the curried 'add' function with the value 5.
// The returned function will take a single argument 'b' and add it to 5.
const add5 = add(5);

// Now, when we call 'add5' with a value (e.g., 3), it adds 5 to the input value, resulting in 8.
const result = add5(3); // 8

Enter fullscreen mode Exit fullscreen mode
  1. Event handling: In event-driven programming, currying can be used to create event handlers with specific configurations, while keeping the core event handling function generic.
const handleClick = buttonId => event => {
   console.log(`Button ${buttonId} clicked`, event);
};

const button1Handler = handleClick(1);
document.getElementById("button1").addEventListener("click", button1Handler);
Enter fullscreen mode Exit fullscreen mode
  1. Customizing API calls: Currying can help create more specific API calls based on a generic API call function.
const apiCall = baseUrl => endpoint => params =>
        fetch(`${baseUrl}${endpoint}`, { ...params });

const myApiCall = apiCall("https://my-api.com");
const getUser = myApiCall("/users");
const updateUser = myApiCall("/users/update");

// Usage:
getUser({ userId: 1 });
updateUser({ userId: 1, name: "John Doe" });

Enter fullscreen mode Exit fullscreen mode
  1. Higher-order functions and functional composition: Currying enables the creation of higher-order functions that can be composed to create more complex functionality.
const compose = (f, g) => x => f(g(x));

const double = x => x * 2;
const square = x => x * x;

const doubleThenSquare = compose(square, double);

const result = doubleThenSquare(5); // (5 * 2)^2 = 100

Enter fullscreen mode Exit fullscreen mode

Currying is a powerful technique that can make your code more modular, reusable, and easier to understand. It allows you to create new functions by partially applying a function's arguments, which can be especially useful when you have a function with many arguments that you need to reuse with different values for some of those arguments.

Top comments (0)