My top 3 favorite higher-order functions In JavaScript

Photo by Usman Yousaf on Unsplash

Higher-order functions are functions that operate on other functions, either by taking them as arguments or by returning them. JavaScript have many built-in higher-order functions like map() and filter(), but you can also create your own higher-order functions.

In this article, I will talk about three higher-order functions in JavaScript: map(), filter() and reduce(). They are all introduced in ES6, and they make code shorter and simple.

The Map Method

This method creates a new array with the result of calling a callback that is provided as an argument for every element in that array. Lets look at an example of how we can populate an array with objects using for loop and map so that you can see the difference between them.

You see the difference? it is much easier and better to use map than the for loop in this case. I also used the arrow function syntax, if you are not familiar with that you can read this article Arrow Function

The Filter Method

This method creates a new array with all the elements that pass the test provided by the callback function. The filter method makes it easy to filter an array of elements.

The Reducer Method

The reduce method iterate over an array of elements and returns one single value. This method takes two arguments, the first one is the reducer function that you provide and another optional one is the initialValue.

The reducer function can take four arguments: accumulator, currentValue, currentIndex and sourceArray.

The first time the function is called, the accumulator will be equal to either the first value in the array or the initialValue if you provided one.

The accumulator is the value that we will end up having at the end, and the currentValue is the current element being processed in the array.

In this example, I used reduce to get the sum of the numbers inside the variable. This is a very basic example, but there are a lot more to do with reduce.

Wrap up

Map, Filter and reduce are very useful in JavaScript, and they allow you to write simple and shorter code as compared to other traditional ways like the for loop. I hope that you learned something from this article. This is just an overview of these methods if you want more details there are a lot of resources out there to dive deep into them.

I write about topics related to web development.