Higher Order Functions

Higher Order Functions

Map, Filter, and Reduce

So, what are higher-order functions?

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

Example-Map, Filter, and Reduce

Map- It creates a new array by calling a function for every array element. It calls a function once for each element in an array. It does not execute the function for empty elements and does not change the original array.


Screenshot_39.jpg output- Screenshot_40.jpg

The above example shows how easily we can get the desired result using the map function.

Filter-It creates a new array filled with elements that pass a test provided by a function.


Screenshot_41.jpg Output-


Reduce- It executes a reducer function for the array element. It returns a single value and the function's accumulated result.

Example- for explaining this I will first show you how to get the result without reduce the function and then I will show you how you can get the same result with reduce function. Then will compare the two approaches.


Output- Screenshot_44.jpg

In line number 5, I used a normal approach and in line number 17 I used reduce function to get the same result.

In line number 17 you can see that I have used 'acc' it is used to accumulate the value and it serves the same purpose as 'sum' in line number 8. Then 'curr' is in line 17. It is the current value that we are getting while iterating over the array. It has the same purpose as what 'arr[i]' is providing us in line number 8.

We can also user Map and filter functions at the same time.


Screenshot_45.jpg Output- Screenshot_46.jpg

We can also get the same result using Reduce function also.


Output- Screenshot_46.jpg

This was all about Map, filter, and reduce functions. I have learned all this from the Namaste JavaScript series by Akshay Saini. If you want to fall in love with JavaScript then you should learn from this.