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:
noisy
is a function that takes a reference to another function f
and returns a new function that wraps f
so that it's call and return values are logged to the console.
val
is the result of the function f
being called, where f
is a function reference that is passed when noisy
is called.
To go step by step:
// noisy accepts argument f (where f itself appears to be a function)
function noisy(f) {
// noisy returns a new function that takes an argument arg
return function(arg) {
// when this new function is called, it logs to console
console.log("calling with", arg);
// the function you originally passed to noisy is now called, with the return value stored in val
var val = f(arg);
// return value val also logged to console
console.log("called with", arg, "- got", val);
// return value val is returned from the generated function
return val;
};
}
// noisy is called with the inbuilt function Boolean and the argument 0 (to test the boolean value of 0)
noisy(Boolean)(0);
Another use case could be something like this:
function someFuncToMonitor(someArg) {
return someArg + 1;
}
monitoredFunc = noisy(someFuncToMonitor);
result = monitoredFunc(5);
// calling with 5
// calling with 5 - got 6
So in short calling monitoredFunc
calls your someFuncToMonitor
function for you and tells you about the call and the results.