The solution here is simple. NEVER call parseInt()
without specifying the desired radix. When you don't pass that second parameter, parseInt()
tries to guess what the radix is based on the format of the number. When it guesses, it often gets it wrong.
Specify the radix like this and you will get the desired result:
parseInt("08", 10) == 8;
As to what rules it uses for guessing, you can refer to the MDN doc page for parseInt()
.
If radix is undefined or 0, JavaScript assumes the following:
- If the input string begins with "0x" or "0X", radix is 16
(hexadecimal).
- If the input string begins with "0", radix is eight
(octal). This feature is non-standard, and some implementations
deliberately do not support it (instead using the radix 10). 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.
So, according to these rules, parseInt()
will guess that "08"
is octal, but then it encounters a digit that isn't allowed in octal so it returns 0
.
When you pass a number to parseInt()
, it has nothing to do because the value is already a number so it doesn't try to change it.