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