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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With