Higher order functions basically are functions that operate on other functions by returning them or taking them as argument... Getting familiar with higher order functions are important because it help to enforce a declarative approach instead of imperative in performing various tasks. Assume we want to iterate over an array(lets call this array people) to find specific persons above a certain age, say 18+ The normal imperative approach goes something like this:
let people = [
{name: "John", age: 35},
{name: "Doe", age: 12},
{name: "Mike", age: 18},
{name: "Ada", age: 23},
{name: "Donald", age: 17},
]
let result = [];
for(let i=0; i < people.length; i++) {
let person = people[i];
if(person.age >= 18) result.push(person);
return result;
}
The code above is unnecessarily ambiguous and could also be error prone, However with Higher order function, this can be drastically simplified and made less ambiguous. Lets see how? First we declare a helper function to iterate over a list ( an array in this scenario) and then we call this helper, passing the list as an argument and a predicate( which is another function) to determine the outcome of our intent. The helper function looks something like this...
function filter(array, test) {
var result= [];
for(var i=0; i < array.length; i++) {
if(test(array[i]))
result.push(array[i]);
}
return result;
}
Now the previous procedure can be simplified thus:
let result = filter(people, person => (person.age >= 18))
Not just that we can simplify code with higher order function, now we can reuse the same function even for other procedures, think about another scenario where our custom filter could also be applied. Good news is javascript provides quite a few handful higher order function for filtering, mapping, reducing an array and so on..., and these methods are super useful and way more efficient than the custom one described here. You can check it out this blog post