1

I recently thought about defining a function to copy the functionality of isNaN out of boredom when I found out, that Number(undefined) equals NaN</code>, but if you doNumber(undefined) === NaNyou getfalse`.

I even tried (typeof Number(undefined)) === (typeof NaN) which returns true.

What is JavaScript doing here?

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
G_hi3
  • 588
  • 5
  • 22

1 Answers1

3

The constant NaN is never equal to anything, including NaN. The value of typeof NaN is "number", because NaN is a number constant.

The value of Number(undefined) is NaN. You can use isNaN() to verify that, or simply:

var x = Number(undefined);
if (x !== x) alert("It's NaN!");
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • OP figured out that last line on his own: _"when I found out, that `Number(undefined)` equals `NaN`"_ ;-) – Cerbrus Jun 29 '15 at 13:40
  • @Cerbrus maybe he'll trust me instead of himself :) – Pointy Jun 29 '15 at 13:40
  • Good point, some times, an outside _"yeap, that's correct"_ helps! – Cerbrus Jun 29 '15 at 13:41
  • Just to add, that although `typeof NaN` is `"number"`, but `NaN instanceof Number` is `false`. JavaScript WAT! – ducin Jun 29 '15 at 13:41
  • 1
    @tkoomzaaskz that's true, but `17 instanceof Number` is also `false`. Neither `NaN` nor `17` are object instances. – Pointy Jun 29 '15 at 13:42
  • @Pointy true, but it's counterintuitive anyway :-) normal languages don't mess with types as much as JS does. – ducin Jun 30 '15 at 13:34