Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an isNaN() function in JavaScript but no isUndefined()?

Tags:

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).

like image 545
MemLeak Avatar asked Oct 17 '14 13:10

MemLeak


People also ask

What does isNaN () in JavaScript do?

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

What is the difference between isNaN () and number isNaN ()?

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 .

Why is NaN === NaN false?

Because Not a Number is not a number, and is not equal to anything, including Not a Number.

What value is returned by the isNaN () method?

isNaN() method returns true if the value is NaN , and the type is a Number.


1 Answers

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:

  1. Let num be ToNumber(number).
  2. ReturnIfAbrupt(num).
  3. If num is NaN, return true.
  4. 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 
like image 107
James Donnelly Avatar answered Sep 19 '22 15:09

James Donnelly