Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them.

There are a lot more higher order functions than what will be covered in this article, but these are good ones to get you up and running as a beginner. These standard array methods are forEach() , filter() , map() and sort() .

  1. **forEach( ): **This is used when you want to operate on or interact with any element inside of an array. Basically works like the_ for loop._

N.B- I’d be using examples to illustrate each method so you can get a clearer picture, and also just printing to the console to keep the examples as simple and basic as possible.

Example: Lets say in an array of a group or friends, and we want to loop through that array and print to the console each element of that array.

Using a for loop ;

const friends = ['Toyin', 'Olumide', 'Fola', 'Tola'];

for ( let i=0; i < friends.length ; i++) {
  cosole.log (friends[i])
};

The action same as above can be achieved using theforEach() method as seen below;

const friends =  ['Toyin', 'Olumide', 'Fola', 'Tola'];

friends.forEach(function(name) {
  console.log(name)
};

What the forEach() method simply does is to take in a function as an argument and loop through each item in the array without using iteration[i].

This is really awesome when the ES6 arrow functions are used, our code is reduced to a single line that is clean and maintainable. As seen below:

const friends =  ['Toyin', 'Olumide', 'Fola', 'Tola'];

friends.forEach(name => console.log (name));

2. **_filter( ) : _**Just like the name implies, it is used to filter out elements of an array that do not meet the conditions set in the callback function passed as an argument. The callback function passed to the filter() method accepts 3 parameters: elementindex, and array , but most times only the element parameter is used.

**Example : **In an array showing a group of friends and their ages, lets say we want to print to the console the friends that can drink assuming the age limit for drinking is 18. Using a for loop without high order functions;

const friends = [
  {name : 'Toyin', age: 24},
  {name : 'Olumide', age: 14},
  {name : 'Fola', age: 12},
  {name : 'David', age: 42}
];
for ( let i=0 ; i<friends.length ; i++) {
   if (friends[i].age > 18) {
    console.log(`${friends[i].name} can drink`);
 }
};

Now using the filter() method :

const friends = [
  {name : 'Toyin', age: 24},
  {name : 'Olumide', age: 14},
  {name : 'Fola', age: 12},
  {name : 'David', age: 42}
];
friends.filter (function (friend) {
  if (friend.age > 18){
   return true;
 } 
});

#functional-programming #beginners-guide #javascript #higher-order-function #es5-vs-es6 #function

Higher-Order Functions Beginners Should Be Familiar With.
1.45 GEEK