Higher order functions in ES6/Javascript

What is higher order function?

Higher-order function is a function that receives a function as an argument or returns the function as output.

Advantage of higher-order function

  1. The higher-order functions are faster than normal function
  2.  Simple syntax and easy to understand

List of higher-order function

  1. forEach
  2. Map
  3. Filter
  4. Reduce
  5. Sort

forEach

The foreach functions call once for all the array elements and foreach is provide clean code compare to the normal for loop

In this example, we are going to print all the array elements present in the array.
let arr = [1,2,3,4,5,6];
Without Higher-order function
for(let i=0;i<arr.length;i++){
  console.log(arr[i])
}
With Higher-order function
arr.forEach((value,index)=>{
  console.log(value)
})

Map 

The map function calls once, for all the array elements and create a new array with the result and return it.

In this example, we are going to multiply the value with 2 of all the array values and store it into the new array
let arr = [1,2,3,4,5,6];
Without Higher-order function
let newArr = [];
for(let i=0;i<arr.length;i++){
   newArr.push(arr[i]*2)
}
console.log(newArr)
With Higher-order function
let newArr1 = arr.map(value => value*2)
console.log(newArr1)

Filter

The filter function also calls once, for all the array elements and return an array with passed value in the test

In this example, we are going to get the value above 3

let arr = [1,2,3,4,5,6];
Without Higher-order function
let newArr = [];
for(let i=0;i<arr.length;i++){
  if(arr[i] > 3) {
    newArr.push(arr[i])
  }
 
}
console.log(newArr)
With Higher-order function
let newArr1 = arr.filter(value => value > 3)
console.log(newArr1)

Comments