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
- The higher-order functions are faster than normal function
- Simple syntax and easy to understand
List of higher-order function
- forEach
- Map
- Filter
- Reduce
- 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
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 = [];With Higher-order function
for(let i=0;i<arr.length;i++){
if(arr[i] > 3) {
newArr.push(arr[i])
}
}
console.log(newArr)
let newArr1 = arr.filter(value => value > 3)
console.log(newArr1)
Comments
Post a Comment