Higher-Order Functions

A higher-order function is a function that does stuff with other functions. That is, it either takes at least one function as an argument or it returns a function. (Or both.)

JavaScript’s Array.prototype.map is a familiar example:

function square(x) {
    return x * x;
}

let numbers = [1, 2, 3, 4, 5],
    squares = numbers.map(square);

console.log(squares); // 1,4,9,16,25

Here, numbers.map applies the square function to every element in the numbers array and returns a new array with the results. We call the function “map” because we think of its operation as mapping each value in the original array into the new array, transforming the value using a mapping function.

A higher-order function that returns a function is perhaps less intuitive. Here’s a simple but contrived JavaScript example:

function lessThan(x) {
    return y => y < x;
}

let lessThan100 = lessThan(100);

console.log(lessThan100(50)); // true
console.log(lessThan100(500)); // false

Here, lessThan is a function that returns another function. We immediately call it with 100 to create a function called lessThan100, and then that function, when called, returns a Boolean value that describes whether its argument is less than 100.

Many popular programming languages now have what we call “first-class functions”. That just means that you can do things like we’re talking about: passing functions as arguments, returning them from other functions, assigning them as variables, etc. The language treats functions as first-class citizens.

Passing functions as arguments has become pretty common, in my experience. I regularly see functions that do this, often for mapping or filtering data.

Functions that return functions seem far less common. I rarely see them in the wild. Yet.