Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

isNaN function in nodejs

Tags:

node.js

nan

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!

like image 825
azero0 Avatar asked Jun 06 '14 09:06

azero0


People also ask

What is the isNaN () method?

isNaN() The Number. isNaN() method determines whether the passed value is NaN and its type is Number .

What is the difference between NaN and isNaN in JavaScript?

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 .

Is NaN in JS?

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.

Is NaN == NaN?

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.


3 Answers

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") {

}
like image 116
Esailija Avatar answered Sep 21 '22 05:09

Esailija


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.

like image 20
Phil H Avatar answered Sep 22 '22 05:09

Phil H


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.

like image 25
Uberbrady Avatar answered Sep 22 '22 05:09

Uberbrady