4

In Javascript

parseInt(null) returns a NaN
parseNumber(null) also returns a NaN

isNaN('abcd') returns true, as 'abcd' is of course not a number,
isNaN(5) returns false

but strangely

isNaN(null) returns false, which is odd as implies it is a number, but as we saw in the parseNumber it was seen by that as NaN

There appears to be an inconsistency between the way null is viewed by parseInt and by isNaN one sees it as NaN and the other sees it as a Number. Why are they inconsistent?

Mickey Puri
  • 835
  • 9
  • 18

1 Answers1

3

The first thing that happens in isNaN() is that the argument is coerced to a number. That is, it's as if the function looked like:

function isNaN(n) {
    n = +n;
    // ...
}

When null is coerced to a number, the value is 0. That's not NaN.

The isNaN function really should not be used as a test to see if a value is a number; that's not what it's for. It's for testing to see if a number — that is, something you know is a number — is NaN.

In modern runtimes, there's Number.isNaN(), which does not perform that type coercion. Of course, with that, null is still not NaN.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • And then the other part of this is that `parseInt` coerces the input to a string so that, in the end, both functions convert `null` to something else. – DocMax Jan 19 '18 at 00:05
  • @DocMax right. Passing `null` to `parseFloat()` does return `NaN`, but I would still consider that to be a little fragile. – Pointy Jan 19 '18 at 00:06
  • Oh, absolutely! The fact that it returns `NaN` is more a happy accident than it is the function doing what you would expect given the input. – DocMax Jan 19 '18 at 00:12
  • @Pointy thanks for explaining why it returns the result. So really the use case for isNaN is rather specialised. The top result in google for testing if a variable is not a number was https://www.mkyong.com/javascript/check-if-variable-is-a-number-in-javascript/ and here they suggested using isNaN so perhaps due to the naming of isNaN there appears to be some confusion. – Mickey Puri Jan 19 '18 at 06:59
  • @Pointy its good to know why its behaving this way. but the expectation created by its name, needs to match its behaviour. or else it kind of feels wrong. Perhaps the isNaN should not coerce a null to a 0 and should treat null as a special case – Mickey Puri Jan 19 '18 at 07:02
  • @MickeyPuri understand that the term `NaN` comes from the IEEE 754 floating point system. It's a set of bit patterns that are invalid, and therefore "not numbers". – Pointy Jan 19 '18 at 14:23