Higher-Order Functions In JavaScript

Understand the Higher-Order Functions and how to use them in JavaScript

blog-cover

While learning JavaScript you might have come across different JavaScript Higher Order Functions. And it seems to be complicated to understand at the very first time. And yeah it is complicated for beginners as well as intermediates.

But understanding these Higher-Order Functions makes life easier. These functions are extensively used in JavaScript.

*Let's understand the Higher-Order Function in Javascript...*

Higher-Order Funtions

Higher-Order Functions are the functions that return another function as an argument.

Some Higher-Order Functions are Array.prototype.map, Array.prototype.reduce and Array.prototype.filter .

Array.prototype.map()

The `map()` method creates a new array by calling the callback function provided as an argument.

Let's look at some examples:

example 1:

We have one array of numbers and we have to create new array which double the value of each element in array1. So here we will use map() to solve this problem.

const arr1 = [1, 2, 3, 4];
const result = arr1.map((x) => {
return x * 2;
})
console.log(result); // 2, 4, 6, 8
example 2:

Here we have array with birth year of a different person, so now we will create new array with their ages.

const birthYear = [1975, 1997, 2002, 1995, 1985];
const ages = birthYear.map(year => 2018 - year);

console.log(ages); // [ 43, 21, 16, 23, 33 ]

Array.prototype.reduce

Reduce() is one of the most useful methods in JavaScript. Reduce() is used to summarizing the total of an array.

Reduce() method accepts four parameters: accumulator, currentValue, currentIndex and sourceArray.

An accumulator is equal to the initial value if provided and currentValue is equal to the first element in the array.
example 1:

If we have to sum an array of numbers,

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

Array.prototype.filter

filter() creates a new array with all elements that satisfies the condition provided in callback function.

This filter() accepts three arguments: array, index and element.

example 1:

We have an array that contains objects with name and age. We will create new array with full age which are greater than or equal to 18.

const persons = [
{ name: 'Peter', age: 16 },
{ name: 'Mark', age: 18},
{ name: 'John', age: 27 },
{ name: 'Jane', age: 14 },
{ name:'Tony', age: 24},
];
const fullAge = persons.filter(person =>
person.age >= 18);

console.log(fullAge);

Hope you have understood the Higher-Order Function in Javascript. 😀