A higher-order function is a function that can take another function as an argument, or that returns a function as a result.
Here we will talk about some Higher Order function of JavaScript. Take a note that, this blog is only to use by me, so I am not gonna explain everything here. Also, I am gonna use the word Function instead of Method to keep the JavaScript earlier convention. You can follow this if you have enough understanding with JS.
Contents we are going to cover:
  1. forEach
  2. filter
  3. map
  4. sort
  5. reduce

Let’s think of an array of object in JS. We will call this array companies and this array will hold the company name and established year. Below you can see the example of this array:

var companies = [{
        name: "ABC Company",
        established: 1999
    },
    {
        name: "DEF Company",
        established: 1951
    },
    {
        name: "GHI Company",
        established: 1921
    },
    {
        name: "JKL Company",
        established: 1970
    },
    {
        name: "MNO Company",
        established: 2001
    },
    {
        name: "PQR Company",
        established: 1912
    }
];

Now we will execute this array using the Higher Order Functions. First thing first, let’s start with the forEach function.

1. forEach works with only an array. It takes all the values/keys/elements in it’s callback function and iterate with each element of that array. It’s more faster than using the normal for loop. Here is a very basic example of forEach function:

// forEach
companies.forEach(function (value) {
    console.log('Company Name: ' + value.name + ' Established Year: ' + value.established);
});

Note: We can see from the example that the callback function is taking a value parameter which provides the value of the each element of the array. We can pass another 2 parameters with this callback function. The second one we can pass is the index number of each element and the third one is the whole array itself.

2. filter function is the magic of getting some specific data from a lot of data inside an array. Let’s see the example below:

// filter
var filteredArr = companies.filter(function (elem) {
    if (elem.established < 2000) {
        return elem;
    }
});

console.log(filteredArr);

Note: From the above example, we can see the filter function is taking a callback function which is also taking a parameter, this parameter is referring to each element of our array. Then w are filtering the array by our own condition. After being filtered, each of the filtered element is being stored in an another array. This function is more faster and conventional than using for loop here.