Vinay Kumar

Higher order functions

Higher order function is a function which accepts function as one of its argument and/or returns a function as its result. Filter, map and reduce are few examples of higher order functions. Higher order functions are made use in abstracting a generalized solution.

Let's assume there is an array of integers and you need to exclude odd numbers from the array. A simple solution would be

function filterEvenNumbers(arr){
    const result = [];
    for(let i=0; i<arr.length; i++){
       if(arr[i] % 2 === 0){
            result.push(arr[i]);   
       }
    }
    return result;
}

filterEvenNumbers([1,2,3,4]);

Now let's say you need to exclude even numbers from the given array. Again one of the possible solution would be

function filterOddNumbers(arr){
    const result = [];
    for(let i=0; i<arr.length; i++){
       if(arr[i] % 2 !== 0){
            result.push(arr[i]);   
       }
    }
    return result;
}

filterOddNumbers([1,2,3,4]);

If you observe the above two functions, one can conclude that apart from the condition supplied to the if statement, the rest of the steps are similar. Let us try to create an abstraction by implementing a custom higher order filter function. The function will accept an array and a function as its arguments.

In our custom filter function, the array items are iterated using for loop and in every iteration the function passed as the argument is executed with array item supplied as argument. This level of abstraction enables us to provide dynamic check condition in the function supplied as argument to the higher order function.