Search code examples
javascripthigher-order-functionsconfirmation

How does this "higher-order functions" thing works in Javascript


From the book Eloquent Javascript by Marijn Haverbeke, there is this example while introducing the concept of higher-order functions:

function greaterThan(n) {
  return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true

I'm not quite sure how this works... probably answering my own question, but this is how I see it:

  • First, greaterThan(n) is called in this line, assigning its value to the greaterThan10 variable:

    var greaterThan10 = greaterThan(10);
    
  • This makes the function stored as greaterThan10 looks like:

    function greaterThan(10) {
      return function(m) { return m > 10; };
    }
    
  • Then, when you call greaterThan10(11) you are calling the function above, which translates to:

    function greaterThan(10) {
      return function(11) { return 11 > 10; };
    }
    

    Hence returning True as the result as 11 > 10 is true indeed.

Could someone confirm whether I'm correct or not? Also, if someone can provide further details and comments on how this higher-order functions work in JavaScript, that would be greatly appreciated.


Solution

  • You're correct, from a level of understanding, but it's evaluated slightly differently.

    var greaterThan10 = greaterThan(10);
    

    This line doesn't make the function stored as greaterThan10 "look like" anything - it creates a new function, passing in the variable n to it, so that greaterThan10 becomes a function that looks like

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

    When you call it, you are calling this function directly, not going through the original function at all anymore.