Why is there an isNaN()
function in JavaScript whilst isUndefined()
must be written as:
typeof(...) != "undefined"
Is there a point I don't see?
In my opinion its really ugly to write this instead of just isUndefined(testValue)
.
isNaN() returns true if a number is Not-a-Number. In other words: isNaN() converts the value to a number before testing it.
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 .
Because Not a Number is not a number, and is not equal to anything, including Not a Number.
isNaN() method returns true if the value is NaN , and the type is a Number.
There is simply no need for an isUndefined()
function. The reason behind this is explained in the ECMAScript specification:
(Note that the NaN value is produced by the program expression NaN.) In some implementations, external code might be able to detect a difference between various Not-a-Number values, but such behaviour is implementation-dependent; to ECMAScript code, all NaN values are indistinguishable from each other.
The isNaN()
function acts as a way to detect whether something is NaN
because equality operators do not work (as you'd expect, see below) on it. One NaN
value is not equal to another NaN
value:
NaN === NaN; // false
undefined
on the other hand is different, and undefined
values are distinguishable:
undefined === undefined; // true
If you're curious as to how the isNaN()
function works, the ECMAScript specification also explains this for us too:
- Let num be ToNumber(number).
- ReturnIfAbrupt(num).
- If num is NaN, return true.
- Otherwise, return false.
A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X !== X. The result will be true if and only if X is a NaN.
NaN !== NaN; // true 100 !== 100; // false var foo = NaN; foo !== foo; // true
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