In this article, you will learn about forEach, map, filter, sort and reduce Higher Order functions in JavaScript.

What is a Higher Order Function?

A higher order functions is a function that accepts another function as an argument and/or returns a function.

Two advantages of higher-order function are concise code and reusability. 😎

Higher order functions in JavaScript

You will learn about following Higher Order Functions in JavaScript with examples:

  • forEach()
  • map()
  • filter()
  • sort()
  • reduce()

NOTE: Arrays provide a number of useful higher-order functions. These higher order functions can work with both array of primitive types and objects. 😃

forEach()

With the help of forEach higher order function, you can loop over the elements in an array. In simple words, it provides something like a for/of loop as a higher-order function.

Let’s assume, we have the following array to work with:

let singleFruits = ["Apple", "Orange", "Banana", "Pineapple", "Avocado"];

Example
Let’s iterate the elements of singleFruits array without higher order function:

for (let i = 0; i < singleFruits.length; i++) {
    console.log(singleFruits[i]);
}

// OR

for (let fruit of singleFruits) {
    console.log(fruit);
}

Both will have same output:

Apple
Orange
Banana
Pineapple
Avocado

Now, let’s iterate the elements of singleFruits array with higher order function:

singleFruits.forEach(fruit => console.log(fruit));

Output:

Apple
Orange
Banana
Pineapple
Avocado

Wow 😱!!!
The difference is clear in both with and without higher order function code.

map()

Higher-order function map() is similar to forEach() function, but the only difference is map() function returns an array. 😉

Let’s take the same array singleFruits for this example:

let singleFruits = ["Apple", "Orange", "Banana", "Pineapple", "Avocado"];

Example
As you can see in above array, each element is singular. Let’s make them plural 😃 using map() higher-order function:

let fruits = singleFruits.map(fruit => fruit + "s");
console.log(fruits);

Output:

["Apples", "Oranges", "Bananas", "Pineapples", "Avocados"]

Another Example, let’s use the same array fruits and create new array FRUITS with all fruits in UPPERCASE 😉

let FRUITS = fruits.map(fruit => fruit.toUpperCase());
console.log(FRUITS);

Output:

["APPLES", "ORANGES", "BANANAS", "PINEAPPLES", "AVOCADOS"]

In above example as you can see, we can manipulate the array elements by using array methods in map() higher order function in JavaScript.

filter()

As the name states, we can use the filter() higher order function in JavaScript to filter out the data as per our requirement. 🤠

Let’s take the same array singleFruits for this example:

let singleFruits = ["Apple", "Orange", "Banana", "Pineapple", "Avocado"];

Example
We want only those fruits which start with ‘A’, let’s filter 😉:

let fruitStartsWithA = singleFruits.filter(fruit => fruit.startsWith("A"));
console.log(fruitStartsWithA);

Output:

["Apple", "Avocado"]

Let’s take another example, this time we will filter out those fruits which have more than 6 characters:

let fruits2 = singleFruits.filter(fruit => fruit.length > 6);
console.log(fruits2);

Output:

["Pineapple", "Avocado"]

sort()

The sort() higher order function can be used to arrange or organize elements in ascending or descending order.

Let’s assume, we have an array of numbers:

let nums = [23, 56, 33, 99, -1];

Sort Numbers

Example
By default, sort() method sorts in ASCENDING order.

console.log(nums.sort());

// OR

console.log(nums.sort((n1, n2) => n1 - n2));

Output:

[-1, 23, 33, 56, 99]

If you want to sort in DESCENDING order, then:

console.log(nums.sort((n1, n2) => n2 - n1);

Output:

[99, 56, 33, 23, -1]

Sort Strings

Example
Let’s take the same array singleFruits for this example:

let singleFruits = ["Apple", "Orange", "Banana", "Pineapple", "Avocado"];

In some browsers, sort() may work directly when sorting in ASCENDING order but it may not work while sorting in DESCENDING order. So, in that case use the localeCompare() function to compare the strings.

console.log(singleFruits.sort());

console.log(singleFruits.sort((f1, f2) => f1.localeCompare(f2)));

Output:

["Apple", "Avocado", "Banana", "Orange", "Pineapple"]

To sort the strings in DESCENDING order:

console.log(singleFruits.sort((f1, f2) => f2.localeCompare(f1)));

Output:

["Pineapple", "Orange", "Banana", "Avocado", "Apple"]

reduce()

As its name suggests a reduce() higher order function will reduce the output and will only return one value. 😯

The reduce() higher-order function takes two arguments, the first one is a function that contains two parameters, accumulator and current value. The second one is an initial value (if this value is left blank then the reduce function will consider the first element of an array as the initial value).

Let’s take the same array nums for this example:

let nums = [23, 56, 33, 99, -1];

Example
Let’s find the sum of all numbers in the nums array using a regular function:

let sum = 0;

for(let n of nums ) {
    sum += n;
}

console.log(sum);

Output:

210

Let’s do the same thing but using reduce() function:

sum = nums.reduce((acc, n) => acc + n);

console.log(sum);

Output:

210

For more JavaScript related posts, click here.

For Higher Order Functions in JavaScript tutorials, check out the YouTube playlist by clicking here.

Categorized in: