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 thegreaterThan10variable:var greaterThan10 = greaterThan(10);This makes the function stored as
greaterThan10looks 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
Trueas the result as11 > 10is 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.
nis becoming a closure variable