Tuesday, June 16, 2020

isNaN is not the same as Number.isNaN

Since JavaScript is an untyped programming language, a variable can contain data of any type at any time. But sometimes you need to know what type the data is. Something I have done in the past, is use the 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);
}


0 comments:

Post a Comment

 
Blogger Templates