Higher-Order Function in JavaScript

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:

  1. It uses one or more functions as parameters
  2. It returns a new function as a parameter

JavaScript1.jpg

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:

  1. It takes a function as an argument
  2. 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.

JavaScript2.jpg

You will find use of Higher-Order functions very often in JavaScript. I hope you find this article useful. Thanks for reading.
 

Up Next
    Ebook Download
    View all
    Learn
    View all