Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion between isNaN and Number.isNaN in javascript

I have a confusion in how NaN works. I have executed isNaN(undefined) it returned true . But if I will use Number.isNaN(undefined) it is returning false. So which one i should use. Also why there is so discrepancy in the result.

like image 558
Pranjal Diwedi Avatar asked Oct 11 '22 12:10

Pranjal Diwedi


People also ask

Is NaN and Number isNaN?

The Number. isNaN() method determines whether the passed value is NaN and its type is Number . It is a more robust version of the original, global isNaN() .

What is isNaN function in JavaScript?

isNaN() method returns true if a value is Not-a-Number. Number. isNaN() returns true if a number is Not-a-Number. In other words: isNaN() converts the value to a number before testing it.

Why is isNaN false?

That isNaN(" ") is false is part of the confusing behavior of the isNaN global function due to its coercion of non-numbers to a numeric type. From MDN: Since the very earliest versions of the isNaN function specification, its behavior for non-numeric arguments has been confusing.

How do you check if a value is NaN or not?

The math. isnan() method checks whether a value is NaN (Not a Number), or not. This method returns True if the specified value is a NaN, otherwise it returns False.


1 Answers

To quote from a ponyfoo article on numbers in ES6:

Number.isNaN is almost identical to ES5 global isNaN method. Number.isNaN returns whether the provided value equals NaN. This is a very different question from “is this not a number?”.

So isNaN just checks whether the passed value is not a number or cannot be converted into a Number. Number.isNaN on the other hand only checks if the value is equal to NaN (it uses a different algorithm than === though).

The String 'ponyfoo' for example is not a number and cannot be converted into a number, but it is not NaN.

Example:

Number.isNaN({});
// <- false, {} is not NaN
Number.isNaN('ponyfoo')
// <- false, 'ponyfoo' is not NaN
Number.isNaN(NaN)
// <- true, NaN is NaN
Number.isNaN('pony'/'foo')
// <- true, 'pony'/'foo' is NaN, NaN is NaN

isNaN({});
// <- true, {} is not a number
isNaN('ponyfoo')
// <- true, 'ponyfoo' is not a number
isNaN(NaN)
// <- true, NaN is not a number
isNaN('pony'/'foo')
// <- true, 'pony'/'foo' is NaN, NaN is not a number
like image 60
nils Avatar answered Nov 07 '22 23:11

nils