DEV Community

Midhun
Midhun

Posted on

Function Currying In Javascript Get it simple 🍲

Hai what is function Currying , Curried Functions 😳 ya ... it's sound like spicy πŸ’ ,there are actually some useful .

oke .. We will start from the basics what are functions

Function is something they simply take input from one side processes inside give output from another side

                input ->([processes])-> Output
Enter fullscreen mode Exit fullscreen mode

Consider a simple function add two number

let add = (x,y)=>x+y
console.log(add(1,2))

3
Enter fullscreen mode Exit fullscreen mode

Let's curve the function add()

Using currying, a function is transformed from being callable as f(a, b, c) to being callable as f(a)(b)(c).

Is it correct that add(x,y) should be transformed into add(x)(y)? πŸ₯Έ

Yes πŸ‘ Currying is when you break down a function that takes multiple arguments into a series of functions that each take only one argument.

Lets Code ..

function curry(f) { // curry(f) does the currying transform
  return function(x) {
    return function(y) {
      return f(x, y);
    };
  };
}

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

let curriedAdd=curry(add)

console.log(curriedAdd(1)(2))

3
Enter fullscreen mode Exit fullscreen mode

😳 why it called Curried
Maybe fist method you added some salt second one added some spice third some water .. πŸ˜‚ ya it helps to call a method as multiple parts like

let c =curriedAdd(5)
c(3)
8
Enter fullscreen mode Exit fullscreen mode

You can see that the implementation is straightforward: it's just two wrappers.

  1. The result of curry(func) is a wrapper function(x)
  2. When it is called like curriedSum(1), the argument is saved in the Lexical Environment, and a new wrapper is returned function(y).
  3. The wrapper is then called with 2 as an argument, and it passes the call to the original sum.

Uses of currying function
a) It helps to avoid passing same variable again and again.
b) It is extremely useful in event handling.

Top comments (2)

Collapse
 
shyam1319 profile image
Shyam Lal

Awesome πŸ‘Œ

Collapse
 
midhunz profile image
Midhun

thank you