Functional Programming in JavaScript- Currying

Currying is used to transform a function with many parameters to a function with less parameters. This is accomplished by binding some arguments of the main function so it can be reused when the function is called again.

This technique is helpful when you want certain arguments to be fixed for a series of functions.
For example if you write a function that prints that a group of people are good at things. You can set it up like this:


var greatWizards = function(groupName, subject) {
  console.log(groupName + ' are good at ' + subject);
};

greatWizards('Wizards', 'Javascript');
// Wizards are good at Javascript
greatWizards('Wizards', ‘magic’);
// Wizards are good at magic

You see that the argument “Wizards” is passed every time we call greatWizards. Applying currying removes the need to do just that.


//With currying one argument never changes. It removes the need to pass it when the function is called.
function greatWizards(groupName) {
  return function(subject) {
    console.log(groupName + ' are good at ' + subject);
  };
}

var wizardMagic = greatWizards("Wizards");

wizardMagic("Javascript");
// Wizards are good at Javascript

wizardMagic("magic");
// Wizards are good at magic

wizardMagic("dancing");
// Wizards are good at dancing

Apparently, it is true that Wizards are great at dancing

This is the basics of currying in JavaScript.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s