This is somewhat explained in the Mozilla reference documentation (emphasis mine):
If parseInt
encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt
truncates numbers to integer values. Leading and trailing spaces are allowed.
...
If radix
is undefined or 0 (or absent), JavaScript assumes the following:
- If the input string begins with "0x" or "0X",
radix
is 16 (hexadecimal) and the remainder of the string is parsed.
- If the input string begins with "0",
radix
is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt
.
- If the input string begins with any other value, the radix is 10 (decimal).
If the first character cannot be converted to a number, parseInt
returns NaN
.
Note how the first bullet point is different to the rest - it says "the remainder of the string is parsed". I take that to mean:
parseInt("0xfoo")
is treated as equivalent to
parseInt("foo", 16)
regardless of what "foo" is - in your case. So parseInt("0x")
is equivalent to parseInt("", 16)
.
So, here are your examples and an explanation of the output:
// radix is inferred as 8 or 10 (implementation-dependent)
// Parsing stops at "x" which is invalid in either radix.
// The first character was valid, so the result is 24 or 18.
parseInt("024x2")
// radix is inferred as 8 or 10 (implementation-dependent)
// Parsing stops at "b" which is invalid in either radix.
// The first character was valid, so the result is 0.
parseInt("0b")
// radix is inferred as 16, but then parsing *restarts* at
// an empty string. There's no valid first character at this
// point, so the result is NaN
parseInt("0x")
The ECMA standard provides much more detail but the Mozilla description is probably simpler to understand. The ECMA version corresponds with my understanding of "the remainder of the string is parsed" too - see step 10 of the description.