I’m writing a function that needs to test if the argument passed is a number. I’m a novice so I just wrote something like this:
if (typeof num !== "number") {
return false;
}
I looked at someone else’s code for the same purpose and they just had something like this:
if (!num) {
return false;
}
I find this confusing. If zero was passed to the function, wouldn’t !num evaluate as true? How does this second chunk of code robustly test the type of the num argument?
Yes it would, and also if
NaNor any falsey non-number value.It doesn’t. It only tests the “falseyness” of the value. Every falsey value will give a
trueresult to theifstatement.Those values are:
false""0NaNnullundefinedAny other value will fail the
ifcondition.(Of course all this is reversed if you don’t negate the value with
!)