Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain to me how this function works?

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.

like image 979
Robby_rob Avatar asked Dec 15 '22 11:12

Robby_rob


1 Answers

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

like image 182
Tushar Avatar answered Dec 17 '22 01:12

Tushar