简体   繁体   中英

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.

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.

I also got confused while reading the example but later on reached the conclusion as below:

In chapter 3: functions, it has been explained how to declare a function using the arrow notation ( => ). The arrow notation comes after the list of parameters, and if there is only one parameter then the parentheses can be ommitted around the parameter list. So, m is a parameter and not a function name.

So, after the first call to greaterThan(10) , greaterThan10 essentially becomes

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

After the second call, greaterThan10(11) , it becomes

function (11) { return 11 > 10; }

11 > 10, which returns true.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM