isNaN
function for this.
Take this (bad?) example. If the variable
myData
is a number, then we want to format it to 2 decimal places. Otherwise, we just want to display it as is. One way to do that would be:
if (isNaN(myData)) {
displayString(myData);
else {
displayDecimalNumber(myData);
}
But then along comes the linter complaining about isNaN
:
So I blindly accept its suggestion and change it to
Number.isNaN
. But now there's a problem because now it's trying to format my string data as a number. What happened?
The problem is that the global
isNaN
does not behave the same way as Number.isNaN
.
The global
isNaN
function converts the value to a Number, then tests it.
Number.isNaN
does not convert the value and will return true for any value that is not of type Number.
So maybe a better way to write this code would be:
if (typeof myData === 'number') {
displayDecimalNumber(myData);
} else {
displayString(myData);
}