Back to blog

So what is currying in Javascript?

·2 min read·
JavascriptEngineering Concepts

Currying is a technique in functional programming where a function with multiple arguments is transformed into a sequence of functions, each taking a single argument.

This allows for partial application of arguments, creating new functions with fewer parameters.

In JavaScript, you can implement currying using closures. Here's a detailed example to demonstrate how to curry a function in JavaScript

// Step 1: Define the function to be curried
function add(a, b, c) {
  return a + b + c;
}
 
// Step 2: Create a currying function
function curry(fn) {
  return function curried(...args) {
    if (args.length >= fn.length) {
      // If all arguments are provided, call the original function
      return fn(...args);
    } else {
      // If not all arguments are provided, return a new function
      return function (...moreArgs) {
        return curried(...args, ...moreArgs);
      };
    }
  };
}
 
// Step 3: Curry the add function
const curriedAdd = curry(add);
 
// Step 4: Use the curried function
console.log(curriedAdd(1)(2)(3)); // Output: 6
console.log(curriedAdd(1, 2)(3)); // Output: 6
console.log(curriedAdd(1)(2, 3)); // Output: 6
console.log(curriedAdd(1, 2, 3)); // Output: 6

In the example above, we have a function add that takes three arguments. We then define a curry function that takes a function fn as its argument. Inside the curry function, we check if all the arguments are provided. If they are, we call the original function fn with the provided arguments. If not, we return a new function that takes additional arguments and recursively calls curried with the accumulated arguments.

Finally, we curry the add function using curry(add), and we can use the resulting curriedAdd function to add numbers by passing arguments in multiple steps or all at once.

I hope this explanation helps you understand how to curry a function in JavaScript! Let me know if you have any further questions.

Enjoyed this article?

Get weekly insights on software development, architecture patterns, and industry best practices.