Higher Order Functions in JavaScript

3 min read Original article ↗

Filter

Lets get to it. In enterprise grade software, we sometimes want to filter on cute dogs.

Press enter or click to view image in full size

We could use a for-loop for this. Where we would iterate over each dog and filter based on the cute boolean.

Press enter or click to view image in full size

However there is a much simpler solution, that is more elegant, that is using the filter function.

Press enter or click to view image in full size

Notice how much simpler this code is. This is because we are using the built in higher order function called filter. Which accepts a function as its parameter, which is used to filter the items in the dogs array. So a higher order function is simply a function that takes in another function in its parameter. We could even go one step further with the above example by separating the parameter into its own function.

Press enter or click to view image in full size

This way we can later reuse the isCuteDog wherever we want to.

Reduce

Let’s say we would like to count have many cute dogs and not cute dogs we have. We could iterate over each dog and put into an object how many dogs are cute and not cute. Or we could make use of the reduce function.

But first lets make an easy introduction to the reduce function, its a method that executes a reducer function on each element of the array, which returns a single output. So lets say we have a list of numbers, that we want to accumulate.

Press enter or click to view image in full size

The reduce function takes in one parameter, a function, the reducer, which has an accumulator (the value which we are adding to), and a currentValue (the current value that is being processed in the array). In the end we end with a value of 8. Here is a great article if you are struggling with this concept.

Press enter or click to view image in full size

Let’s get back to our counter. In this example, we provide a reducer function, that accumulates a object that we call tally, which is an object which you can see at the last line, {} which is the initial value. As we iterate over each item, we check whether or not we have seen a cute or not cute dog before, then we either initiate the value with a 1, or we keep counting the value upwards. In the end we will have an object containing { false: 2, true: 2 }