Javascript: how to create partial functions

1 minute read

Currying and partial application functions are very powerful techniques widely adopted by many functional langagues.

If you work with Javascript you can use the core function bind to easily create partial applications.

Let’s look at an example.

We have an array of objects:

var cities = [{name: "Paris", country: "France"}, {name: "London", country: "UK"}, {name: "Rome", country: "Italy"},{name: "Manchester", country: "UK"}];

and a function that given a city object and a specific country returns true if the city belongs to the given country:

var isIn = function(country, city) {
  return city.country === country;
};

isIn("UK", {name: "London", country: "UK"}) //true

What if we’d like to filter the array looking for cities that are in a specific country?

A partial function is a good approach to solve the problem, and bind makes the creation of it very simple.

The syntax of bind is the following:

fun.bind(thisArg[, arg1[, arg2[, ...]]])

Where the first parameter is the value we want to bound the this keyword to when the created function is invoked while the others are the actual parameters of the bound function.

var UKCity = isIn.bind(null, "UK");//don't need to set the this keyword, just passing null

UKCity({name: "London", country: "UK"}) //true

We can now use the partial function UKCity as argument of the filter function:

var UKCities = cities.filter(UKCity);
//UKCities === [{name: "London", country: "UK"}, {name: "Manchester", country: "UK"}]

//get the list of the Italian cities is as simple as:
cities.filter(isIn.bind(null, "Italy"));
//[{name: "Rome", country: "Italy"}]

In the example the creation of a partial application function allows us to seamlessly compose our initial isIn function with a higher order function like filter to achieve more sophisticated outcomes.

A gist with the whole example code is available here.

Updated: