Function Composition in JavaScript with Array.prototype.reduceRight

Functional programming in JavaScript has rocketed in popularity over the last few years. While a handful of its regularly-promoted tenets, such as immutability, require runtime workarounds, the language’s first-class treatment of functions has proven its support of composable code driven by this fundamental primitive. Before covering how one can dynamically compose functions from other functions, let’s take a brief step back.

What is a Function?

Effectively, a function is a procedure that allows one to perform a set of imperative steps to either perform side effects or to return a value. For example:

function getFullName(person) {
  return `${person.firstName} ${person.surname}`;
}

When this function is invoked with an object possessing firstName and lastName properties, getFullName will return a string containing the two corresponding values:

const character = {
  firstName: 'Homer',
  surname: 'Simpson',
};

const fullName = getFullName(character);

console.log(fullName); // => 'Homer Simpson'

It’s worth noting that, as of ES2015, JavaScript now supports arrow function syntax:

const getFullName = (person) => {
  return `${person.firstName} ${person.surname}`;
};

Given our getFullName function has an arity of one (i.e. a single argument) and a single return statement, we can streamline this expression:

const getFullName = person => `${person.firstName} ${person.surname}`;

These three expressions, despite differing in means, all reach the same end in:

  • creating a function with a name, accessible via the name property, of getFullName
  • accepting a sole parameter, person
  • returning a computed string of person.firstName and person.lastName, both being separated by a space

Combining Functions via Return Values

As well as assigning function return values to declarations (e.g. const person = getPerson();), we can use them to populate the parameters of other functions, or, generally speaking, to provide values wherever JavaScript permits them. Say we have respective functions which perform logging and sessionStorage side effects:

The post Function Composition in JavaScript with Array.prototype.reduceRight appeared first on SitePoint.

Powered by WPeMatico