What Are Higher Order Array Methods in JavaScript?
Tags: javascript, beginners, es6, arrays
Published: 2020-08-09 17:10:54

If you’ve been programming for **any** amount of time, you would be familiar with arrays. They are the among the first data structures taught in most programming lectures/courses. For good reason too, because they are pretty easy to work with. But in case you work in JavaScript, using arrays can be made a whole lot simpler with the help of some useful higher order methods!

The reason that these are called **Higher Order Methods** is that they can accept/return another function. If this seems a tad bit confusing, then it’s important that you understand why [**functions are first class citizens**](https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function#:~:text=A%20programming%20language%20is%20said,a%20value%20to%20a%20variable.) in JavaScript. It is just a fancy way of saying that functions are just like any other type of data, which can be stored, accessed, passed as arguments and even returned from another method!

The following image does a pretty good job at describing what a higher order function is

![Credit: @joelnet on twitter](https://cdn-images-1.medium.com/max/2000/1*jCvQfxJQHXstWN7vE2tVww.png)_Credit: @joelnet on twitter_

<hr>

A quick heads up. These higher order methods will require the usage of callbacks and they will be a lot easier to write, if you are familiar with the **arrow syntax** of **ES6**. In case you’re not, you can go through the following section to see what it is. Here’s a pretty basic example:

```
// normal function definition
function add(a, b) {
  return (a + b)
}

// arrow syntax
const add = (a, b) => (a + b);
```

You can convert a normal function definition into its arrow syntax counterpart, using the following steps:

1. Remove the `function` keyword and replace it with either `const` or `let` or `var` . We can do this because functions are _first-class objects in JavaScript_. (**Note:** In case you want an [anonymous function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions), just remove the `function` keyword and move to step 2)

2. Next, put an arrow symbol `=>` in front of the arguments’ list, to indicate that the code following it will be the body of the function.

3. After this, you can type curly braces and write the function body as usual. But, if your function body has just 1 line (the return statement), you can skip the curly braces, skip the return keyword, and just type out the expression that needs to be returned!

4. For functions with no argument, just leave empty brackets before the `=>` symbol.
   `const alertMsg = () => alert("This is just an example!")`

5. Lastly, if you are handling just 1 argument in the function, you can skip the parenthesis around it.
   `const squared = x => (x \*\* 2)`

<hr>

Now that you have brushed up on the arrow syntax, let’s begin to understand some higher order array methods!

-   **forEach()**: Think of it as a less verbose implementation of a `for loop`. It invokes a function on **each** array element, and its syntax goes like this:

```
array.forEach((element, index) => {
    // some operations on the element
    // maybe you want to use the index of the element
});
```

In case you want to see a pretty contrived example, take a look at the following example.

![Example for forEach()](https://cdn-images-1.medium.com/max/2000/1*6EfY0yi-rp2UhFYOor-c6g.png)

-   **map()** : If you’ve understood forEach(), then this is a piece of cake! It functions exactly like a forEach, but **returns a new array** unlike the forEach() method. The syntax is as follows:

```
const returnedArr = array.map((currentEle) => {
    // some operation on currentEle
});
```

It’s slightly different to the forEach() method, but you should be able to use them interchangeably for most applications. In case you want to know about the differences, you can go through [this article](https://www.freecodecamp.org/news/4-main-differences-between-foreach-and-map/#:~:text=forEach%28%29%20does%20not%20mutate%20the%20array%20on%20which%20it%20is%20called.&text=The%20map%28%29%20method%20returns,original%20array%20with%20the%20callback%20.).

<hr>

**reduce()** is especially useful whenever you need to compute a single value based on the data stored in an array. As the name suggests, this reduces an array into a single value, but can be a little tricky to use! The callback function that this method accepts, works on each element of the array in a way that reduces the array to a single value. The syntax is as follows:

`const reducedVal = array.reduce(callback, initialVal);`

Here, `callback` needs to take **2 arguments**. The first argument acts as an **accumulator**, whose value persists throughout the process. The second represents the **current value** of the array.

A simple example can be to find the sum of the array elements.

![Example for reduce()](https://cdn-images-1.medium.com/max/2000/1*3Q5uRxWDs6WqLG7z7EEcbw.png)

In the above example, the `reduce()` method has a callback function called `reducerCallback` (very creative, I know!). This callback needs to have 2 arguments, I called mine `acc` and `current` .

The basic idea is that the value in `acc` is **persisted** each time the callback method is executed. This means that if the `reducerCallback` is executed for the 2nd element of demo , then the values of the arguments `acc` and `current` are, **12** and **34** respectively. The callback then adds these two values and returns them. This returned value is now the new value stored in `acc`

So, for the 3rd callback execution, the values of `acc` and `current` are **46** and **54**. You can see how the array’s values are being used to get to a single value.

But I also mentioned a second argument called `initialVal` in the syntax. This is set as the initial value of the `acc` variable. In case you do not specify any `initialVal` argument, `acc` will take the array element at the **0th index** as its **default initial value**.

Here is an article that gives you a verbose explanation about the workings of the `reduce()` method
{% medium https://medium.com/javascript-in-plain-english/4-practices-to-help-you-understand-array-reduce-f3138cfef095 %}

<hr>

The next method that is used often is **filter()**. It is very helpful if you want to extract a sub-array from a larger array, based on some common property. The syntax is as follows

`const filteredArr = array.filter(callback);`

Here `callback` accepts an argument `current` which results is a **boolean value being returned**. Based on the return value, the `current` value is **pushed** to `filteredArr`.

For example, suppose you want to separate the even numbers from a given array.

![Example to filter out even numbers](https://cdn-images-1.medium.com/max/2000/1*tsmUpHe6n0N0z8i_yS2SgA.png)

Here, the `callback` function is anonymous and it accepts an argument that represents the current element of the `demo` array. If the `callback` returns **`true`** then `item` is **pushed** to the resultant array `filteredArr`.

Here, for all the even numbers in `demo` , our `callback` returns a **0(zero)**, which is **falsy** in nature. Hence, all the even numbers are omitted from `filteredArr` . On the other hand, all the odd numbers return **1(one)** which is equivalent to true . This way, our `demo` array has been filtered!

You can go through the following article to see some more examples.
{% medium https://codeburst.io/learn-understand-javascripts-filter-function-bde87bce206 %}

<hr>

Lastly, let’s understand a higher order method used most often. **sort()** is a method that doesn’t quite work like we assume it would!

You would imagine that the following code works by sorting the array in ascending order by default, right?

```
const demo = [100, 20, 89, 3, 17];
demo.sort();
```

But, it returns the array `[100, 17, 20, 3, 89]` . “What? Why?”, I hear you say. Let’s understand why **sort()** has such a behavior.

**sort()** assumes that all the array elements are `String` by default, and sorts the elements based on the UTF-16 code values, in case it is not passed any callback!

This is why 100 will come before 20. In order to sort an array in a more traditional way (i.e, as numbers) we will need to use a callback function as follows `array.sort(callback)`

The `callback` needs to accept **2 arguments** and return a numeric value indicating how these 2 arguments need to be stored in the _sorted array._

Here is an example to sort an array of elements in ascending order:

![Example to sort array in ascending order](https://cdn-images-1.medium.com/max/2000/1*ioM69QBxs5bKFAiwntFHQQ.png)

-   If `callback(a, b)` returns less than 0, `a` comes before `b`.

-   If `callback(a, b)` returns 0, `a` and `b` are left at their current index.

-   If `callback(a, b)` returns greater than 0, `b` comes before `a`

Note that `callback(a, b)` must always return the same value when given a specific pair of elements `a` and `b` as its two arguments.

Here `a` and `b` are the 2 consecutive elements of the `demo` array, which are continuously compared in the `callback`. Here, if you wanted to sort the array in descending order, all you need to do is change the `callback` to the following.

![Example to sort an array in descending order](https://cdn-images-1.medium.com/max/2000/1*sOMfKibDvOub_g1mL0d9ag.png)

In case you want to look at more examples of how to use the **sort()** method, you can go through the following article.

{% medium https://medium.com/madhash/demystifying-the-mysteries-of-sort-in-javascript-515ea5b48c7d %}

<hr>

All said and done, these methods are a sliver of all the higher-order array methods offered by JavaScript. Although these are the methods that you’ll use on a more regular basis, it is not a futile attempt to go through the rest of the methods!

In case you wish to learn more about any of these array methods, or if you want to learn some more higher order methods, I’d suggest that you go to the [MDN Docs](https://developer.mozilla.org/en-US/), as it provides a pretty thorough explanation of all the methods that JavaScript has to offer.