I'm relatively new to JS and I've also just been reading through Eloquent Javascript and I found it easier to understand once I understood the calling of the function (answering your point 1):
noisy(Boolean)(0);
The noisy(Boolean)
creates a new function and the (0)
is after it because it is being passed as an argument into that new function. If you refer back to the greater than example:
function greaterThan(n) {
return function(m) { return m > n; };
}
var greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
It could also be called in this way:
greaterThan(10)(11);
I hope that clarifies your first question about why it was called that way.
For the second question. The f
in:
var val = f(arg);
is the Boolean
function that was passed into noisy
when noisy(Boolean)
was entered. It was then used as the argument in the noisy function. I also didn't realise that Boolean could be a function in itself and not just a data type. As others have said - it converts the argument you gave it into a Boolean value and returns the result.
Therefore val
becomes Boolean(arg)
which becomes Boolean(0)
which evaluates to false
. If you try call noisy(Boolean)(1);
you will see it return true
. The console.log("called with", arg, "- got", val);
simply logs the argument (0 in this case) and the result of evaluating it (false).
In effect, it has changed the Boolean function into one that logs the argument and result, as well as returning the result.
I hope this helps. Just writing it has helped my own understanding.