Featured

isNaN() vs Number.isNaN()

 NaN (an acronym for not a number) is a JavaScript datatype used to describe entries that are not numbers.

isNaN() and Number.isNaN() are both JavaScript methods used to check if an entry is not a number.

isNaN()

It converts a parameter into the number data type and then checks if it is a number or not. It returns a boolean value that indicates whether a value is the reserved value NaN. That is to say, it returns 'true' if the value if the parameter is not a number and 'false' if it is.

Number.isNaN()

It also returns a boolean value that indicates whether a value is the reserved value NaN. But like the isNaN() method, it doesn't force the parameter into the number data type. Hence only parameters that are both of the number data type and are NaN result in true.

Comparison Examples:

Example 1: 


The isNaN() method returns true for the parameter because after forcing into a number data type it is still not a number. While we get false from the Number.isNaN() because although the parameter is not a number it is not in the number data type.

Example 2:

Although they both give false values they are for different reasons. The isNaN() method returns false because after converting the parameter to the number data type we get a value of 1 (true converts to 1) which is a number. Whereas Number.isNaN() gives a false value because true is of the boolean data type, not the number data type.

Example 3:

We  have a true value for both methods because the parameter is of the number data type, for Number.isNaN(), and it is also NaN

Example 4:

It gives a false value for both of them because the parameter is a number.

Conclusion

The Number.isNaN() method returns true only if the parameter is both NaN and of the number data type, else it returns false. While the isNaN() method returns true if after converting to the number data type the parameter is NaN. Hence whatever returns true for Number.isNaN() also returns true for isNaN().





Comments