If you are learning JavaScript, you must have come across the term Higher-Order Functions.
Higher-Order Functions are extensively used in JavaScript. If you have been programming in JavaScript for a while, you may have already used them without even knowing.
List of Higher-order functions in Javascript
- forEach
- Map
- Filter
- Reduce
- Some
- Sort
Let’s take a look at some examples of built-in higher-order functions and see how it compares to solutions where we aren’t using Higher-Order Functions.
Let's use the below array, it contains the country and country code.
let arrayCollection = [{country:"United States",countryCode:1},
{country:"Canada",countryCode:1},
{country:"Russia",countryCode:7},
{country:"Switzerland",countryCode:41},
{country:"Brazil",countryCode:55},
{country:"Malaysia",countryCode:60},
{country:"Singapore",countryCode:65},
{country:"Japan",countryCode:85},
{country:"India",countryCode:91},
{country:"North Korea",countryCode:850}];
let arrayCollection1 = [];
without Higher order function
for(let i=0;i<arrayCollection.length;i++){
arrayCollection1.push(arrayCollection[i].country);
}
1. forEach
forEach is run the given function of each array element
In our example, we will copy the name of the countries and push it into the new array(arrayCollection1)
arrayCollection.forEach(country => {The higher order code is very simple compared to the normal for loop
arrayCollection1.push(country.country);
});
2. Map
The map method is creating a new array with the result and return it.
let arrayCollection1 = arrayCollection.map(val => val.country);
console.log(arrayCollection1);
Comments
Post a Comment