Reputation: 2310
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!
Upvotes: 14
Views: 26719
Reputation: 490
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.
Upvotes: 6
Reputation: 177
isNaN is a "is Not a Number" function, it returns true when no number are give to it as parameter, and false when a number is given
Upvotes: 0
Reputation: 20141
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.
Upvotes: 4
Reputation: 140220
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") {
}
Upvotes: 19