DEV Community

Aishanii
Aishanii

Posted on

Currying in javascript(๐Ÿ”–)

As we were learning before, functions in javascript are

  • Treated as sub-programs (execution context)
  • First class objects (they have methods & properties)

Currying is basically:
function (a,b,c) --> function (a)(b)(c)

1. Currying using closures๐Ÿ‘‡

function mix(f) { //closure, f is batter here

  return function(a) {

    return function(b) {

      return f(a, b);
    };
  };
}

function batter(a, b) {
  return a + b;
}
cook=mix(batter)
console.log(cook('flour ')('banana puree'));
Enter fullscreen mode Exit fullscreen mode

Image description

2. Currying using function methods- bind()๐Ÿ‘‡

As we have discussed before, bind() is function method used to get a function copy to be used with fixed arguments or this reference.

function multiply(a , b){
    console.log(a)
    console.log(b)
    return a*b
}

getTwice=multiply.bind(this, 2)
console.log(getTwice(7))
Enter fullscreen mode Exit fullscreen mode

We can change the number but getTwice will have a=2 fixed.
Image description

Currying requires the function to have a fixed number of arguments.

โญRead about functional programming concepts here.
I just had to link this one:
โญClosures, currying & functions in js

Top comments (0)