Higher-Order-Function : JavaScript
Hey Reader! Whenever you write a large program, it is very costly. Not only because of the time it takes but also, size involves complexity, and complexity, in turn, introduces high chances of mistakes (bugs) into programs. Resolving these bugs is even harder due to the complexity of the program.
So to write large programs, you can create a small-small block of programs as functions to perform certain actions and then use this block of code in other functions to make the code simpler to understand. It also reduces the chances of errors. This is known as Functional Programming. In functional programming, we think and code in terms of functions.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. For example, array.prototype.map, array.prototype.filter and array.prototype.reduce are some of the Higher-Order functions built into the language. You can also create your own higher-order functions like this. Probably the greatest benefit of higher-order function is greater reusability.
Let's look at an example to understand how it works:
Array.prototype.map
The map() method creates a new array with the results of calling a function for every array element. It calls the provided function once for each element in an array, in order.
Note: map() method does not change the original array.
Let’s say we have an array of numbers and we want to create a new array that contains double of each value of the first array.
Without higher order function
const a=[1,2,3];
const b=[];
for(let i = 0; i < a.length; i++) {
b.push(a[i] * 2);
}
// prints [ 2, 4, 6 ]
console.log(b);
Now lets do it with:
With higher order function
const a= [1, 2, 3];
const b= a.map(function(item) {
return item * 2;
});
console.log(b);
We can make this even shorter using arrow function syntax.
const a = [1, 2, 3];
const b = a.map(item => item * 2);
console.log(b);
It's clearly visible that the code becomes more clean and concise using higher-order functions.
Now let's create our own higher-order function.
We here create a function multiplier that takes factor as an argument and returns another function.
function multiplier (factor) {
return function (x) {
return x * factor;
};
};
// here doubler gets the function returned by a multiplier with a factor value as 2
let doubler = multiplier(2);
//output
console.log(doubler(5));
// here doubler(5) returns 10.
To make it more clear, doubler in the above code refers to:
doubler = function(x){
return x*2;
}
In this code, we can reuse our function multiplier multiple times to create tripler and so on which will save us a lot of time.
I hope this blog helped you. Thank you for reading.
Keep Learning. Keep Growing.