Currying in JS

Currying in JS

Functional programming is a style of programming which bought the ability to take functions as parameters and return function without any issues to the code .This ability of passing and receiving functions bought some things along with it

  • Currying
  • H.O.C (Higher order Functions)
  • Pure functions

The concept we would be going through here would be currying

What is currying ?

currying is a concept of functional programming where we can transform a function with multiple parameters into a sequence of nested functions. It returns a new function that expects a new argument line. What it would do is that it would keep returning untill the parameters are finished.

Lets take a simple example

function multiply(a, b, c) {
   return a * b * c
}

In the above example we can see that the function takes three parameters which in turn give us the result . Now lets see another way of writing the same using currying

function multiply(a) {
  return (b) => {
          return (c) => {
          return a * b * c
      }
  }
}
console.log(multiply(2)(4)(6));
// console.log(48)

what we have done here is to convert single function call to multiple function call that are in series . To understand this better please check the code below

const mul1 = multiply(2)
 const mul2 = mul1(4)
 const mul3 = mul2(6)
 // console.log(48)

Idea behind currying is that to take a function and derive the function that returns specialized function.