The concept of High Order Functions in Javascript

Question:

I'm reading Eloquent Javascript to get a javascript base. I was getting pretty good at it, as the fundamentals don't change compared to other languages ​​like data types (int, string, bool, objects, arrays). But I arrived at the part of Abstraction . I know this is also part of other languages, being one of the bases for many design patterns out there,

however I didn't understand the concept of High Order Functions .

Let's go to 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 taking them as arguments or returning them, are called higher-order functions).

function greaterThan ( n ) {

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

}

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

// → true

What I didn't understand, mainly, was this example there. Mainly the arguments part.

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

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

Answer:

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

Generally speaking, functions like .map() and .filter() are functions that fall into this category, as they take 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 variable's state, it is simply a tool to be chained, that is, a higher-order function, that is, a tool to create other functions. Hence it is called "abstraction" as 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 takes a number and returns a boolean.

Scroll to Top