HIGHER ORDER FUNCTIONS

Higher Order Functions

Higher-order functions are functions that take other functions as arguments or return functions as their results.

Any function that is passed as an argument is called a callback function.

One of the great advantages of using higher order functions when we can is composition.

We can create smaller functions that only take care of one piece of logic. Then, we compose more complex functions by using different smaller functions.

This technique reduces bugs and makes our code easier to read and understand.

By learning to use higher-order functions, you can start writing better code.

For example, let’s say you want to write a function for multiplication and division. Generally what we will do is write a function for multiplication and another function for division as shown in below example.

Example :

const array = [4, 2, 10, 6]
//Multiplication
const multi = (arr) => {
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push(arr[i]*2);
}
return res;
}
console.log(multi(array)); //Prints: [8, 4, 20, 12]
//Division
const div = (arr) => {
let res = [];
for (let i = 0; i < arr.length; i++) {
res.push(arr[i]/2);
}
return res;
}
console.log(div(array)); //Prints: [2, 1, 5, 3]

There is nothing wrong with above functions but we are repeating same lines of code except logic which make our code difficult to understand and can cuase bugs. To handle this, we can create smaller functions that only take care of one piece of logic. And pass those smaller functions as callbacks in another function which is higher order function as shown in below example.

Example :

const array = [4, 2, 10, 6]
const common = (arr, fun) => {
let res = [];
for(let i=0; i<arr.length; i++){
res.push(fun(arr[i]))
}
return res
}
const multi = input => input * 2;
const div = input => input / 2
console.log(common(array, multi)); //Prints: [8, 4, 20, 12]
console.log(common(array, div)); //Prints: [2, 1, 5, 3]

In above example, we have three functions which are common, multi and div. The common function is the higher order function because it is taking other two functions as arguments which are call back functions.