For example Number("Infinity")
returns Infinity
because it recognizes it as of type number, so I was wondering if Number("NaN")
returns NaN
for the same reason that Number("potato")
returns NaN
or because it recognizes it as a number like it does "Infinity"?
No, there is no special case for "NaN"
like there is for "Infinity"
, you get NaN
with "NaN"
for the same reason you get NaN
for "potato"
.
You can consult the spec JavaScript uses to see the internal logic for how Number()
should work. Looking at Number() from the ECMAScript spec (the spec JavaScript follows), you can see it calls ToNumeric() which in turn calls ToNumber(). This eventually returns the result of calling StringToNumeric(). In this abstract operation, it does the following:
- Let literal be ParseText(str, StringNumericLiteral).
- If literal is a List of errors, return NaN.
- Return the StringNumericValue of literal.
The first step tries to parse your input string ("NaN"
) using a goal of StringNumericLiteral, however, if you look at this grammar, "NaN" does not conform to it (since a StringNumericLiteral
must either start with a whitespace character, be one of the 0-prefixed literals such as 0b
/0B
, 0x
/0X
, 0o
/0O
, a decimal or Infinity
, with +/-
symbols being optional for those two). Since "NaN"
can't be parsed as a StringNumericLiteral
, the ParseText() operation leads to a list with errors being returned, causing point 2 from above to return NaN
.