As a new javascript developer, I have spent some time with this code snippit from Chapter 6 of Eloquent Javascript, I am still trying to understand the following code example :
function negate(func) {
return function(x) {
return !func(x);
};
}
var isNotNaN = negate(isNaN);
document.writeln(isNotNaN(NaN));
Where it particular loses me is the following line, I just don’t understand the call in general and where the variable/value for NaN comes from:
document.writeln(isNotNaN(NaN));
I think xdazz pretty much covered it, but since you said you still don’t get it maybe it would help to hear the explanation in somebody else’s words.
This line:
…declares a variable
isNotNanthat is assigned equal to the result of a call to thenegate()function, passingisNanas a parameter.That parameter
isNanis actually a function as described by MDN, butnegate()would accept any function as a parameter, you could say for examplevar isNotFinite = negate(isFinite);.Now the
negate()function actually creates and returns another function, so after that line runsisNotNanreferences that returned function, which means you can call it asisNotNan(someVal).So then the line:
… calls
isNotNan()and passes itNaNas a parameter, and the result is written out to the document.NaNis a property of the global object. To oversimplify, it is a constant provided to you by the JS environment.Regarding how the
negate()function works, it relies on the concept of “closures”, which means that functions declared insidenegate()have access to its variables and parameters even afternegate()completes. You’ll notice that the returned function references thefuncparameter. So when you call the returned function viaisNotNaN()it can still access that originalfuncparameter that is set to theisNanfunction.The effect is kind of like doing this: