Exploring Currying in JavaScript🚀: Everything You Need to Know

Exploring Currying in JavaScript🚀: Everything You Need to Know

What is Currying?

Currying is a process in functional programming in which we can transform a function with multiple arguments into a sequence of nesting functions. It returns a new function that expects the next argument inline.

In simple, instead of taking all the arguments at a time, takes one argument and returns the new function expecting the other argument and so on till the arguments is fulfilled.

It is a conversion of function from add(a, b, c) --> add(a)(b)(c)

The number of function the arguments takes is called Arity.

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

console.log(add(2,3)); 
//output: 5

The add function takes two argument x and y and returns their sum. Now lets curry the above function.

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

console.log(add(2)(3));
//output: 5

Why it's useful?

👉 Making a function pure reduces the chances of errors and unexpected side effects.

👉 Decomposing a function into smaller, focused functions allows for clearer organisation and easier maintenance.

👉 It divides one function into multiple functions so that one handles one set of responsibility.

Infinite Currying

The concept extends currying to handle an infinite number of arguments by returning a series of functions that can keep adding numbers as needed. The key idea is to use recursion to create a chain of functions that expect additional arguments until the final result is computed.

function sum(a) {
  return function (b) {
    if (b) return sum(a + b);
    else return a;
  };
}
console.log(sum(1)(2)(3)(1)());
//output: 7

The implementation of infinite currying involves defining a base case for recursion to end, typically when there are no more arguments to pass.

Partial Application

The number of nested function that curried function has depends on the argument it received.

function partial(a) {
  return function (b, c) {
    return a + b + c;
  };
}
console.log(partial(1)(2, 3));
//output: 6

In the above code it expects three arguments and it has two nested function unlike our previous one had two arguments and two nested function.This part is know as the partial application.

Currying in JavaScript relies on closures to achieve its functionality.

Thanks for diving into these insights🚀. If you have any feedback or suggestions, I'd love to hear from you❤️.