why is isNaN function in nodejs returning false in the following cases?
isNaN(''),isNaN('\n'),isNaN('\t')
this is very weird.
does somebody have any ideas as I thought isNaN stood for is Not a Number.
can someone please clarify
Thanks in advance!
isNaN() The Number. isNaN() method determines whether the passed value is NaN and its type is Number .
isNaN converts the argument to a Number and returns true if the resulting value is NaN . Number. isNaN does not convert the argument; it returns true when the argument is a Number and is NaN .
In JavaScript, NaN is short for "Not-a-Number". In JavaScript, NaN is a number that is not a legal number. The Number. isNaN() method returns true if the value is NaN , and the type is a Number.
NaN is not equal to NaN! Short Story: According to IEEE 754 specifications any operation performed on NaN values should yield a false value or should raise an error.
Because you are not passing it a number, it will convert it to number. All of those convert to 0
which is 0
and not NaN
Number('')
0
Number('\n')
0
Number('\t')
0
isNaN(0)
false
Note that NaN
does not stand for "not a JavaScript Number". In fact it's completely separate from JavaScript and exists in all languages that support IEEE-754 floats.
If you want to check if something is a javascript number, the check is
if (typeof value === "number") {
}
NaN is a very specific thing: it is a floating point value which has the appropriate NaN flags set, per the IEEE754 spec (Wikipedia article).
If you want to check whether a string has a numeric value in it, you can do parseFloat(str)
(MDN on parseFloat). If that fails to find any valid numeric content, or finds invalid characters before finding numbers, it will return a NaN value.
So try doing isNaN(parseFloat(str))
- it gives me true
for all three examples posted.
isNan()
is designed to help detect things that are 'mathematically undefined' - e.g. 0/0
-
node
> isNaN(0/0)
true
> isNaN(1/0)
false
> isNaN(Math.sqrt(-1))
true
> isNaN(Math.log(-1))
true
The other advice you got here in this question on how to detect numbers is solid.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With