jimm-cl
jimm-cl

Reputation: 5412

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:

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.

Upvotes: 1

Views: 730

Answers (2)

kumarras
kumarras

Reputation: 136

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.

Upvotes: 0

Evan Knowles
Evan Knowles

Reputation: 7501

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.

Upvotes: 3

Related Questions