The concept of High Order Functions in Javascript

9

I'm reading Eloquent Javascript to get a Javascript base. I was understanding well, since the fundamental does not change in relation to other languages, like data types (int, string, bool, objects, arrays). But I came to the Abstraction section. I know that this is also part of the other languages, being one of the bases for many design patterns there,

But I did not understand the concept of High Order Functions .

Let's see the example shown in Eloquent Javascript p. 90:

  

Functions that operate on other functions, either by taking them as   arguments or by returning them, are called higher-order functions.

     

(Functions that operate on other functions, either by taking them as arguments or by returning them, are called high-order functions.)

function greaterThan ( n ) {

  return function ( m ) { return m > n; };

}

var greaterThan10 = greaterThan (10) ;
console . log ( greaterThan10 (11) ) ;

// → true

What I did not understand, especially, was this example there. Mostly part of the arguments.

First it sets greaterThan10 = greaterThan10(10) , and passes argument 10 to this function , and hence it can call VARIAVEL as function ? And the arguments? Will the first argument passed in the definition continue there? (10)

I'm a bit confused, I'd like a slightly simpler explanation, or an example where this concept is more visible.

    
asked by anonymous 01.09.2016 / 20:25

1 answer

12

This concept is very common in functional programming, where the concept is to avoid state and use functions, chaining functions to do what needs to be done by the program. Functions that accept other functions as arguments are called high-order functions .

Generally, functions like .map() and .filter() are functions that fall into this category, since they consume functions as an argument.

Explaining your example:

function greaterThan(n) {
    return function(m) {
        return m > n;
    };
}

Here you have a function that returns a function. This is important. The function does not change a state of a variable, it is simply a tool to be chained or a higher order function, ie a tool to create other functions. Hence it is called "abstraction" because it can be used in N different contexts.

You can then generate another, more specific function by doing

var greaterThan10 = greaterThan(10);

which in practice is the same as:

var greaterThan10 = function(m) {
    return m > 10;
};

This greaterThan10 function will return a Boolean value. In this case the function receives a number and returns a boolean.

    
01.09.2016 / 20:32