Understanding currying in JavaScript  - DattuNaik

Understanding currying in JavaScript - DattuNaik

Currying:

  • Currying is a technique of evaluating function with multiple arguments, into the sequence of functions with a single argument.

  • In other words, when a function, instead of taking all arguments at one time, takes the first one and return a new function that takes the second one and returns a new function which takes the third one, and so forth until all arguments have been fulfilled.

Currying is a transformation of functions that translates a function f(a, b, c) into f(a)(b)(c). So, currying transforms a function with multiple arguments into a sequence/series of functions each taking a single argument.

let's take a simple example...

function sum(a, b, c) {
  return a+b+c;
}
sum(2,3,5) // 10
  • let's how we use currying here...
function sum(a) {
   return function(b){
      return function(c) {
         return a+b+c;
    }
  }
}
sum(2)(3)(5) //  10

We have turned the sum(2,3,5) function call to sum(2)(3)(5) multiple function calls. One single function turned to series of functions.

  • we could also separate this for better understanding
let sum = function (x) {
  return function (y) {
    console.log(x + y);
  };
};
// sum1 = sum(2); we can also do like this
// sum1(6);  // 8
sum(2);
sum(2)(6); // 8
  • Now, some might begin to think that the number of nested functions a curried function has depends on the number of arguments it receives. Yes, that makes it a curry.
  • Closure makes currying possible in JavaScript. Its ability to retain the state of functions already executed gives us the ability to create factory functions.  functions that can add a specific value to their argument.

Advantages of currying

  • Increase Code reusability.
  • Avoid frequently calling a function with the same argument.
  • Make your code easier to refactor

Thanks for reading! Hope you enjoyed learning about currying🔥🔥