Yogesh Chauhan's Blog

Higher Order Functions in JavaScript with Examples

in JavaScript on November 7, 2020

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.

Higher-order functions allow us to abstract over actions, not just values.

They come in several forms. For example, we can have functions that create new functions.

Higher Order Functions in JavaScript: create new functions.

There is a built-in array method, forEach, that provides something like a for/of loop as a higher-order function.

Higher Order Functions in JavaScript: forEach

Furthermore, Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into the language.

Examples

Let’s take a look at different examples of higher order functions.

Array.prototype.map

The map() method creates a new array by calling the callback function provided as an argument on every element in the input array.

The map() method will take every returned value from the callback function and creates a new array using those values.

The callback function passed to the map() method accepts 3 arguments: element, index, and array.

Example 1

Let’s say we have an array of numbers and we want to create a new array which contains double of each value of the first array. Let’s see how we can solve the problem with and without Higher-Order Function.

Without Higher-order function map

Higher Order Functions in JavaScript: Without function map

With Higher-order function map

Higher Order Functions in JavaScript: With function map

We can make this even shorter using the arrow function syntax:

Higher Order Functions in JavaScript: map with arrow function

Example 2

Let’s say we have an array containing the birth year of different persons and we want to create an array that contains their ages. For example:

Without Higher-order function map

Higher Order Functions in JavaScript: without function map

With Higher-order function map

Higher Order Functions in JavaScript: with function map

Array.prototype.filter

The filter() method creates a new array with all elements that pass the test provided by the callback function.

The callback function passed to the filter() method accepts 3 arguments: element, index, and array.

Example

Let’s say we have an array which contains objects with name and age properties. We want to create an array that contains only the persons with full age (age greater than or equal to 18).

Without Higher-order function filter

Higher Order Functions in JavaScript: without filter function

With Higher-order function filter

Higher Order Functions in JavaScript

Array.prototype.reduce

The reduce method executes the callback function on each member of the calling array which results in a single output value.

The reduce method accepts two parameters:

1) The reducer function (callback),

2) and an optional initialValue.

The reducer function (callback) accepts four parameters: currentValue, currentIndex, sourceArray.

If an initialValue is provided, then the accumulator will be equal to the initialValue and the currentValue will be equal to the first element in the array.

If no initialValue is provided, then the accumulator will be equal to the first element in the array and the currentValue will be equal to the second element in the array.

Example

Let’s say we have to sum an array of numbers:

With Higher-order function reduce

Higher Order Functions in JavaScript: without function reduce

Every time the reducer function is called on each value in the array, the accumulator keeps the result of previous operation returned from the reducer function, and the currentValue is set to the current value of the array. In the end the result is stored in the sum variable.

We can also provide an initial value to this function:

Higher Order Functions in JavaScript: with function reduce

Without Higher-order function reduce

Higher Order Functions in JavaScript: without function reduce

As we can see that using High-order function made our code cleaner, more concise and less verbose.

Creating Higher-Order Function

Up until this point, we saw various Higher-order functions built into the language. Now let’s create our own Higher-order function.

Let’s imagine JavaScript didn’t have the native map method. We could build it ourselves thus creating our own Higher-Order Function.

Let’s say, we have an array of strings and we want to convert this array to an array of integers, where each element represent the length of the string in the original array.

Creating Higher Order Functions in JavaScript

In the above example, we created an Higher-order function mapForEach which accepts an array and a callback function fn. This function loops over the provided array and calls the callback function fn inside the newArray.push function call on each iteration.

The callback function fn receives the current element of array and returns the length of that element, which is stored inside the newArray. After the for loop has finished, the newArray is returned and assigned to the lenArray.

Sources


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
perspective property in CSSCSSWhat is Etrieve Flow?MiscellaneousHow to check if checkbox is checked or not using JavaScript?JavaScriptbin2hex() and chr() String Functions in PHPPHPWhy it’s not a good idea to create Number objects in JavaScript?JavaScriptEXISTS and NOT EXISTS in PostgresPostgres