I recently started to learn javascript by myself and I am reading a book called "Eloquent JavaScript". The following code is a sample script in the book which confused me:
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
Can someone please explain the logic of the last two lines? Does the greaterThan10 contain a truth value or it is a function?
2 Answers 2
You define greaterThan10 on the second to last line:
var greaterThan10 = greaterThan(10);
Whatever the greaterThan function returns in this case is what greaterThan10 will evaluate to.
On line 2 we see that greaterThan will return the following function expression:
function(m) { return m > n; }
After replacing the variable n with the value you passed we get this:
function(m) { return m > 10; }
Comments
It can look a little confusing at first, but just keep in mind that functions are objects in JavaScript.
greaterThan(n) is a function that returns an anonymous function with the definition:
function(m) { return m > n; }
Therefore, when we call greaterThan(10) we expect it to return an object that is in fact a function:
function(m) { return m > 10; }
Later on we just assign that object/function to a variable, and call it like we would call any function.
In short, just imagine that we had:
var greaterThan10 = function(m) { return m > 10; };
greaterThan10is a function.