In this article we will have a look at Higher-Order functions in JavaScript.
Before reading this article, you may want to go through the following articles:
Higher-Order function can be defined as follows:
- It uses one or more functions as parameters
- It returns a new function as a parameter
Let us say you have a function as follows:
function FindGreater(a, b)
{
if (a > b)
return a;
else
return b;
}
You will pass this function as an argument to another function. That function will be called a Higher-Order function.
Assume we have created another function with the name IamHigherOrderFunction.
function IamHighorderFunction(functionargument)
{
return function ()
{
var result = functionargument.apply(this, arguments);
turn "I am returned from high function" + result;
}
}
Some important points about the function above are:
- It takes a function as an argument
- It returns a function as output
In the function we are just appending a text to the result of the passed function as an argument. You can call a higher-order function as follows:
var result = IamHighorderFunction(FindGreater);
alert(result(9,5));
You will get output as in the following. We are passing the FindGreater function as an argument to the Higher-order function named IamHigherorderFunction.
You will find use of Higher-Order functions very often in JavaScript. I hope you find this article useful. Thanks for reading.