DEV Community

Aishanii
Aishanii

Posted on

2

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, โ€œnot bad.โ€

Fixing code doesnโ€™t have to be the worst part of your day. Learn how Sentry can help.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay