In http://eloquentjavascript.net/1st_edition/chapter6.html, there is the following example:
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
alert(isNotNaN(NaN));
Knowing only basic Javascript and imperative programming, I am stumped by this programming style. Can someone help me to understand what happens during runtime.
I stepped through the code and inspected variables and found that the value of x
is NaN
. How does it know that the argument to isNaN
should be passed as argument x
of the anonymous function? In the first place, why does the actual parameter NaN of isNotNaN
become the argument to isNaN
(ie while isNaN
expects an argument, why does it take it from the argument of isNotNaN
)?
Best way to understand this might be with seeing what these things actually equal. Notice how func
becomes the passed isNaN
function.
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
/*
isNotNaN = function(x){
return !isNaN(x)
}
*/
alert(isNotNaN(NaN));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With