4

I'm learning to code and I'm trying to understand Higher Order Functions and abstractions. I don't understand how this piece of code runs to return "true".

function greaterThan(n) {
  return function(m) { return m > n; };
}

var greaterThan10 = greaterThan(10);

console.log(greaterThan10(11));

Thanks for the help.

Robby_rob
  • 190
  • 1
  • 11

1 Answers1

12

The function greaterThan returns a function when called. The returned function has access to all the members of the outer function even after the function has returned. This is called closure.

function greaterThan(n) {
    return function (m) {
        return m > n;
    };
}

When following statement is executed

var greaterThan10 = greaterThan(10);

it is converted as

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

So, greaterThan10 is now the function and can be called as

console.log(greaterThan10(11));

Now, value of m is 11 and return 11 > 10; returns as true.

Read more about closures:

How do JavaScript closures work?

Also, I'll recommend following great article to all the JS developers

http://dmitryfrank.com/articles/js_closures

Community
  • 1
  • 1
Tushar
  • 85,780
  • 21
  • 159
  • 179