The Power of Higher Order Functions in JavaScript

  1. Code Composition and Powerful Examples
  2. Taking it a Second Step Further
  3. Taking it a Third Step Further
  4. Taking it Further One Last Time
  5. Conclusion
  6. Source:

A higher order function is a function that either takes another function as an argument or returns a function as the return value.

Higher order functions are widely used in JavaScript and they exist in commonly used functions like .map, .filter, .reduce and .forEach.

You see these when you declare function callbacks as arguments to these array methods:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const arr = [1, 2, 3, 4, 5, 'six', 'seven', 'eight', 'nine', 'ten']

// Duplicate the array
arr.map(function(value) {
return value
})

// Return only the number types
arr.filter(function(value) {
return typeof value === 'number'
})

// Log each value to the console
arr.forEach(function(value) {
console.log(value)
})

// Add the numbers together, avoiding the string types
arr.reduce(function(acc, value) {
if (typeof value === 'number') {
acc += value
}
return acc
}, 0)

But the higher order function isn’t the function you pass in to methods like .map. Methods like .map is the higher order function.

At first, it may seem like a useless way to write code in JavaScript. Why pass in a function and bother returning another function, when you can just avoid all of that and do everything in one function all at once?

The biggest benefit that higher order functions bring to the table are reusability and simplicity. But they also benefit from writing beautiful code.

Code Composition and Powerful Examples

Now that we know what higher order functions look like in code, you might be wondering what were some use cases and where do they begin to shine.

Let’s say we have a list of frogs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
const frogsList = [
// Yes, these frogs are intelligent. They know how to use email
{
name: 'bobTheFrog',
email: '[email protected]',
age: 2,
gender: 'Male',
widthOfTongue: 3,
},
{
name: 'hippoTheFrog',
email: '[email protected]',
age: 10,
gender: 'Male',
widthOfTongue: 11,
},
{
name: 'sally',
email: '[email protected]',
age: 5,
gender: 'Female',
widthOfTongue: 4,
},
{
name: 'george',
email: '[email protected]',
age: 11,
gender: 'Male',
widthOfTongue: 3,
},
{
name: 'lisa',
email: '[email protected]',
age: 19,
gender: 'Female',
widthOfTongue: 15,
},
{
name: 'kentucky',
email: '[email protected]',
age: 18,
gender: 'Male',
widthOfTongue: 13,
},
]

To filter the frogs to a specific gender type without a higher order function, we would have to do something like this:

1
2
3
4
5
6
7
8
function filterGender(gender, frogs) {
return frogs.filter(function(frog) {
return frog.gender === gender
})
}

// filterGender in use
const maleFrogs = filterGender('Male', frogsList)

This is perfectly fine. However, it can be cumbersome if used multiple times in an application. If we had a gigantic app about frogs, filterGender might be used more than once.

Taking it a Second Step Further

If you were to fetch a different list of frogs you’d have to call filterGender again and re-declare your gender as the first argument to filter the new list:

1
2
3
4
5
6
function getFrogs() {
// some logic and returns a new list of frogs
}

const newFrogs = getFrogs()
const moreMaleFrogs = filterGender('Male', newFrogs) // Shucks, I have to write 'Male' again?

To solve this issue, we can use the concept of higher order functions.

1
2
3
4
5
6
7
function filterGender(gender) {
return function(frogs) {
return frogs.filter(function(frog) {
return frog.gender === gender
})
}
}

And now, just like that, we can just assign this gender filterer to a variable and we would never have to declare the same gender when filtering frogs anymore!

1
2
const filterFemaleFrogs = filterGender('Female')
const femaleFrogs = filterFemaleFrogs(frogsList)

Taking it a Third Step Further

If you still aren’t convinced enough of how powerful higher order functions are in the JavaScript language, then lets continue the example to make an even more generic function to create a higher level of reusability:

1
2
3
4
5
function filterFrogs(filter) {
return function(frogs) {
return frogs.filter(filter)
}
}

Previously we had the ability to make a reusable function for a frog’s gender. However, we can go further by abstracting away the logic of the filter function, so that now we can compose and re-use different filter functions!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const filterMaleFrogs = filterFrogs(function(frog) {
return frog.gender === 'Male'
})

const filterAdultFrogs = filterFrogs(function(frog) {
return frog.age >= 10
})

const filterFrogNamesThatStartWithHippo = filterFrogs(function(frog) {
return frog.name.toLowerCase().startsWith('hippo')
})

const filterGmailEmails = filterFrogs(function(frog) {
return /gmail.com/i.test(frog.email)
})

Wow!

Previously we had the amazing ability to re-use a gender filterer function without ever having to declare the same gender type ever again, but now we have the additional abilities of creating and re-using functions of how we want the frogs to be filtered! Amazing!

We can even use them all at once:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function applyAllFilters(...filters) {
return function(frogs) {
let newFrogs = [...frogs]

for (let index = 0; index < filters.length; index++) {
const filter = filters[index]
newFrogs = filter(newFrogs)
}

return newFrogs
}
}

const applyFrogFilterers = applyAllFilters(
filterMaleFrogs,
filterAdultFrogs,
filterFrogNamesThatStartWithHippo,
filterGmailEmails,
)

const combinedFrogsList = [...frogsList, ...frogsList2, ...frogsList3]

const filteredFrogs = applyFrogFilterers(combinedFrogsList)

console.log(filteredFrogs)

/*
result:
{
age: 10,
email: "[email protected]",
gender: "Male",
name: "hippoTheFrog",
widthOfTongue: 11
}
*/

Taking it Further One Last Time

Our applyAllFilters function does the job quite well. However, for huge lists of frogs it might become a heavy task because it runs filter multiple times to get the final result.

We can again use the concept of higher order functions to make a simple, reusable higher order function that is able to make one pass through the entire list of frogs by applying the filters at the same time.

To be more clear, have a look at the for loop code and try to see what’s truly happening behind the scenes:

1
2
3
4
5
6
7
8
9
10
11
12
function applyAllFilters(...filters) {
return function(frogs) {
let newFrogs = [...frogs]

for (let index = 0; index < filters.length; index++) {
const filter = filters[index]
newFrogs = filter(newFrogs)
}

return newFrogs
}
}

The line I want you to look at is this:

1
newFrogs = filter(newFrogs)

That line of code is the same line of code as return frogs.filter(filter) in this function:

1
2
3
4
5
function filterFrogs(filter) {
return function(frogs) {
return frogs.filter(filter)
}
}

This is a problem, because the filter method creates a new array. When we had written this:

1
2
3
4
5
6
const applyFrogFilterers = applyAllFilters(
filterMaleFrogs,
filterAdultFrogs,
filterFrogNamesThatStartWithHippo,
filterGmailEmails,
)

We’re calling the filter method 4 different times. In other words, we’re making JavaScript create four different arrays in memory just to get the final result.

So how can we make JavaScript create just one array to get the same result in the end?

You guessed it. Using higher order functions!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// NOTE: The filter functions are now individual functions (not wrapped with filterFrogs)

const filterMaleFrogs = function(frog) {
return frog.gender === 'Male'
}

const filterAdultFrogs = function(frog) {
return frog.age >= 10
}

const filterFrogNamesThatStartWithHippo = function(frog) {
return frog.name.toLowerCase().startsWith('hippo')
}

const filterGmailEmails = function(frog) {
return /gmail.com/i.test(frog.email)
}

// Credits to: SerjoA
function combineFilters(...fns) {
return function(val) {
for (let i = 0; i < fns.length; i++) {
const filter = fns[i]
const passes = filter(val)
if (passes) {
continue
} else {
return false
}
}
return true
}
}

function composeFrogFilterers(...fns) {
return function(frogs) {
// Credits to: SerjoA
return frogs.filter(combineFilters(...fns))
}
}

const applyFrogFilterers = composeFrogFilterers(
filterMaleFrogs,
filterAdultFrogs,
filterFrogNamesThatStartWithHippo,
filterGmailEmails,
)

const combinedFrogsList = [...frogsList, ...frogsList2, ...frogsList3]

const allFilteredFrogs = applyFrogFilterers(combinedFrogsList)

console.log(allFilteredFrogs)

/*
result:
{
age: 10,
email: "[email protected]",
gender: "Male",
name: "hippoTheFrog",
widthOfTongue: 11
}
*/

Conclusion

I hope you are convinced of how powerful higher order functions are and that by reading this article you gained some more insight on the use cases of this concept! Look out more for more in the future!

Source:

https://jsmanifest.com/the-power-of-higher-order-functions-in-javascript/