Higher Order Functions

When we talk about higher order functions, we mean a function that either:

Takes one or more functions as arguments

Or returns a function as its result

The double-operator function we implemented above is a higher order function, because it takes an operator function as an argument and use it.

Probably you've already heard about filter , map , and reduce . Let's take a look at it.

Filter

Given a collection, we want to filter by an attribute. The filter function expects a true or false value to determine if the element should or not be included in the result collection. Basically, if the callback expression is true , the filter function will include the element in the result collection. Otherwise, it will not.

A simple example is when we have a collection of integers and we want only the even numbers.

An imperative way to do it with Javascript is to…

Create an empty vector evenNumbers

Iterate over the numbers vector

vector Push the even number to the evenNumbers vector

But we can use the filter higher order function to receive the even? function, and returns a list of event numbers:

One interesting problem I solved on Hacker Rank FP Path was the Filter Array problem. The problem idea is to filter a given array of integers and output only those values that are less than a specified value X .

An imperative Javascript solution to this problem is something like that:

We say exactly what our function needs to do: iterate over the collection, compare the collection current item with x , and push this element to the resultArray if it pass the condition.

But we want a more declarative way to solve this problem, and using the filter higher order function as well.

A declarative Clojure solution would be something like this:

This syntax seems a bit strange in the first place, but #(> x %) is just a anonymous function that receives x and compare with each element in the collection ( % represents the parameter of the anonymous function — in this case the current element inside the filter ).

We can also do this with maps. Imagine we have a map of people with name and age . And we want to filter only people over age, meaning people who are more than 21 years old.