3

I just happen to stumble upon a code which checks the typeof of a varable passed to it just like this.

function myNaN(b){

  if(typeof(b) == 'number'){
    // execute some code
  }

}

Whenever I call this function it works fine and passes the if condition if number is being passed.

However when I pass a NaN (which is the output of some other function) to this function the if condition returns true.

My question is it correct that typeof(NaN) == 'number' ? If so, why? Isn't it confusing?

Just try running console.log(typeof(NaN)); in browser console to see what I mean.

ʞɹᴉʞ ǝʌɐp
  • 5,350
  • 8
  • 39
  • 65
  • `Number.isNaN(Number.NaN) === true`. `NaN` is of type `Number`, if you want to know whether it is a `number` or `NaN`, use `isNaN` – Niklas Nov 06 '13 at 14:52

2 Answers2

3

Yes, typeof(NaN) is number. You can check if the value is NaN specifically using the function isNaN.

Guilherme Sehn
  • 6,727
  • 18
  • 35
  • 1
    NaN is a shorthand for "Not a Number" and you get NaN when trying to parse(Int/Float) a string that is not a number. – Udi Cohen Nov 06 '13 at 14:54
1

Why don't you use the: "isNan("1234")" function ? Here is some link if it helps: http://www.w3schools.com/jsref/jsref_isnan.asp

Hitman
  • 588
  • 4
  • 10
  • `isNaN()` attempts to coerce to a number, so you can get some confusing results, like these. `isNaN(null); // false` `isNaN(" "); // false` – Blue Skies Nov 06 '13 at 14:55