1

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.

1
  • 2
    Yes... here n is becoming a closure variable Commented Jul 2, 2015 at 5:31

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.