Writing this in the JavaScript console:
var num42 = "42"; var hello = "hello"; var empty = ""; var nothing = null; console.log(parseInt(num42) + ", " + isNaN(num42)); console.log(parseInt(hello) + ", " + isNaN(hello)); console.log(parseInt(empty) + ", " + isNaN(empty)); console.log(parseInt(nothing) + ", " + isNaN(nothing));
gives you:
42, false NaN, true NaN, false NaN, false
You would think isNaN's behavior should be consistent with parseInt returning NaN...
This is easily explained. isNaN is meant to be called on a number, so "" and null get coerced to 0 before the test for NaN is even done (the same as when you do (+x) or Number(x) on one of these values). parseInt, on the other hand, takes a string, and does not successfully parse "" or "null" as integers.
Posted by: DavidLG | March 13, 2009 at 01:50 AM