DEV Community

Cover image for Higher Order Functions
Raj Kishor Shaw
Raj Kishor Shaw

Posted on

Higher Order Functions

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.

Example-

Image description

Output-

Image description

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.

Example-

Image description

Output-

Image description

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.

Image description

output-

Image description

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.

Example-

Image description
Output-

Image description

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

Image description

Output-

Image description

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.

Top comments (0)