Explain higher order functions in JavaScript


What is a Higher Order Function in JavaScript?

JavaScript being a multi paradigm language, it supports procedural programming, functional programming and object oriented programming. Since it is also a functional programming language javascript handles functions as a first class entities, where functions can be assigned to a variable, set it as an object's property, and can pass them as an argument to another function. This characteristic in javascript helps in implementing Higher Order Functions, which can operate on other functions either by taking them as an argument or by returning them.

Let us take an example and implement it without using any higher order functions.

Example

In the below code, we have a list of numbers and we want to increment each element by 10, to achieve this without using higher order functions, we need to loop through the array using for loop and increment each value by 10 and push the incremented values to a new array. Finally, print the incremented array using console.log()

const numbers = [1, 2, 3, 4, 5];

incrementedNums=[]

for(i=0;i<numbers.length;i++){
   added=i+10
   incrementedNums.push(added)
}
console.log(incrementedNums)

Output

[ 10, 11, 12, 13, 14 ]

Now, let see the same functionality using .map() function which is a higher order function

In this, instead of looping the entire array using for loop, we a higher order function .map() which loops through the array and pass each element in it to a function(add()) which is passed as an argument.

Example

const numbers = [1, 2, 3, 4, 5];

function add(num){
   return(num+10)
}
const incrementedNumbers = numbers.map(add);

console.log(incrementedNumbers);

Output

[ 11, 12, 13, 14, 15 ]

And this is how a map function works. It iterates over an array and executes a provided function once for each array element and return the output as an array. Map() function doesnot change the original array, also it doesnot perform the operation on an empty array.

Below JavaScript functions are some inbuilt Higher Order Functions −

  • map()

  • forEach()

  • filter()

  • reduce()

Let us Look into other methods −

The forEach() Method

forEach method is similar to a map function, where it executes the callback function for each element in the array. The only difference between forEach() and map() is that, map function returns an array output, where as forEach returs undefined, it just iterates through the array.

Example

Below code shows the working of forEach method −

const numbers = [10, 20, 30, 40];

sum=0
numbers.forEach(add)

function add(n){
   sum=sum+n
}
console.log(sum)

Output

100
In the above code, we have taken an array of 4 elements, iterated through it using .forEach() and found the sum of the elements present in it, using a callback function add().

The filter() Method

.filter() method shallow copy the array and filters down the value which pass the condition implemented by the provided callback function. It is an iterative method, which calls the callback function given as an argument for each element in the array and return an output array with the elements which returned truthy value by the callback function.

Example

numbers=[10, 11, 12, 14, 15]

even=numbers.filter(iseven)
function iseven(n){
   return(n%2===0)
}
console.log(even)

Output

[ 10, 12, 14 ]

The reduce() Method

Similar to map and foreach, reduce method also executes a callback function (reducer function) on every element of the array, resulting a single output. In simple terms, reduce method reduces the array to a single value. The Parameter of the reducer function is a callback function, which further has two arguments, accumulator and current value. Where current value is the current iterated value of the array. accumulator accumulates the callback function's output. The final return value is stored in the accumulator

Example

numbers=[10,11,12,13]

total =numbers.reduce(function(acc,el){
   return acc+el
},0)

console.log(total)

Output

46

In the above code, given a array of numbers, and we want to find the sum of the array. we use reduce method which takes a callback function as its argument. As disscussed, this callback function takes two parameters: acc (accumulator) and el (current element)

This callback function is applied to every element in the array. using acc we accumulate the result as we iterate through the array. In this case, callback function simply adds the current element (el) to the accumulator(acc). the 0 passed as the second argument is the accumulator

The map() Method

As Discussed in the earlier section, map() function iterates through an array and apply a callback functionfor every element in the array. Let us consider another example and understand. In below example map function iterates through the given array of numbers and pass them into sqrt function, resulting an output of root values.

Example

numbers=[4,9,16,25,36]

root= numbers.map(Math.sqrt)
console.log(root)

Output

[ 2, 3, 4, 5, 6 ]
(node:328974) [DEP0016] DeprecationWarning: 'root' is deprecated, use 'global'

Updated on: 23-Apr-2024

223 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements