I\'m very new to JavaScript, and I was hoping to get some help with Chapter 5 in the 2nd Ed. of Eloquent JavaScript. Specifically, I ran into the example below:
Code in question:
function noisy(f) {
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
}
noisy(Boolean)(0);
// → calling with 0
// → called with 0 - got false
What happens (kind of like a "magic schoolbus" journey through JavaScript):
noisy(Boolean)(0);
noisy
function is called with the JavaScript built-in function Boolean
as its argument f
.arg
.arg
.f
(which has been memoized within the anonymous function by closure) and store the return value in the variable val
.arg
, followed by the string "- got", followed by val
.val
.noisy(Boolean)
is the anonymous function as described above, with Boolean
playing the role of f
within this anonymous function that was just generated.(0)
is now used to call this newly generated anonymous function with an argument arg
of 0.arg
takes on a value of 0 as the initial step of the anonymous function's invocation.Boolean
function is run with an argument of 0, which returns false
, which is stored into val
.false
(but this value is not used or stored in any way by the example code).Now let's go through the actual lines of code and match them with the above steps:
noisy(Boolean)
The following code within noisy
is executed, with argument Boolean
being passed into noisy
and stored into the variable f
:
return function(arg) {
console.log("calling with", arg);
var val = f(arg);
console.log("called with", arg, "- got", val);
return val;
};
noisy(Boolean)
part of this code noisy(Boolean)(0);
has now been replaced with the return value shown in step 2.noisy(Boolean)(0)
has in effect become [[anonymous function]](0)
.[[anonymous function]](0)
is now executed.As a result, the following lines of code are executed:
console.log("calling with", 0); // because 0 was passed in for arg
var val = Boolean(0); // because Boolean is stored in f
console.log("called with", 0, "- got", false);
// because the Boolean value of 0 is false