Higher Order Functions

A function that operates on another function either by taking them as arguments or by returning them is a higher-order function.

For example Array.prototype.map, Array.prototype.filter and Array.prototype.reduce are some of the Higher-Order functions built into JavaScript.

With functions in JavaScript, you can do the following:

  • Store them as variables

  • Use them in arrays

  • Assign them as object properties(methods)

  • Pass them as arguments

  • Return them from other functions

image info

Higher-Order Functions in Action

Let us take a look at the built-in 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, array and index.

Some examples are given below:

Example 1

Let us consider the following scenario: there is an array of numbers which we would like to create a new array containing double of each value of the first array.

// Without Higher-order function

const array1=[5,6,7];
const array2=[];

for (let i=0; i<array1.length; i++){
    array2.push(array1[i]*2);
}

console.log(array2); //prints [10, 12, 14]

The push method simply adds onto the array from the end of the array.

// With Higher-order function (map)

const array1 = [5,6,7];
const array2 = array1.map(function(item)){
    return item*2;
};

console.log(array2); // prints [10,12, 14]

This could be made shorter using an arrow function syntax:

const array1 = [2, 3, 4];
const array2 = array1.map(item => item*2 );

console.log(array2); //prints [4,6,8]

Example 2#

This example contains an array of birthdays for different people and we want to craete an array with their ages.

// Without Higher-order Function
const birthYear = [1980, 2002, 1996, 1962, 1999];
const ages =[];
for (let i=0; i< birthYear.length; i++){
    let age = 2021- birthYear;
    ages.push(age);
}

console.log(ages); //prints [41, 19, 25, 59, 22]
// With Higher-order Function (map)
const birthYear = [1980, 2002, 1996, 1962, 1999];
const ages=birthYear.map(year=>2021-year);

console.log(ages); //prints [ 41, 19, 25, 59, 22 ]

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, array and index.

Example 1#

In this example we will be looking at an array which contains objects with name and age properties. The aim is to create an array that contains only the persons with full age (age greater than or equal to 18).

// Without Higher-order function
const peeps = [
    { name: 'Peter', age:16 },
    { name: 'Mark', age: 18 },
    { name: 'John', age: 27 },
    { name: 'Jane', age: 14 },
    { name: 'Tony', age: 24 }
];
const fullAge=[];

for(let i=0; i<peeps.length; i++){
    if (peeps[i].age=>18){
        fullAge.push(peeps[i]);
    }

}
console.log(fullAge); /* prints [
    { name: 'Mark', age: 18 },
    { name: 'John', age: 27 },
    { name: 'Tony', age: 24 }
  ]
  */
// Without Higher-order function (filter)

const peeps = [
    { name: 'Peter', age:16 },
    { name: 'Mark', age: 18 },
    { name: 'John', age: 27 },
    { name: 'Jane', age: 14 },
    { name: 'Tony', age: 24 }
];


const fullAge = peeps.filter(peep => peep.age >= 18);

console.log(fullAge); /* prints [
    { name: 'Mark', age: 18 },
    { name: 'John', age: 27 },
    { name: 'Tony', age: 24 }
  ];

  */

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 initalValue.

The reducer function (callback) accepts four parameters: accumulator, cuurentValue, cuurentIndex, sourceArray.

If an initialValue is provided, then the accumulator will be equal to the initialValue and the currentValue will be equal to the second 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 1#

For instance, we have to sum an array of numbers:

// With Higher-order function (reduce)

const arr = [5, 7, 1, 8, 4];
const sum = arr.reduce(function(accumulator,currentValue){
    return accumulator + currentValue;
});

console.log(sum); //prints 25

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.

// With Higher-order function (reduce)

const arr = [5, 7, 1, 8, 4];
let sum = 0;
for(let i = 0; i < arr.length; i++) {
  sum = sum + arr[i];
}
// prints 25
console.log(sum);

Last updated

Was this helpful?