Why is parseInt('60', 10) the same as parseInt('60', 0)?
What does JavaScript convert that 0 radix to?
Why is parseInt('60', 10) the same as parseInt('60', 0)?
What does JavaScript convert that 0 radix to?
From MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)
If the radix is undefined, 0, or unspecified, JavaScript assumes the following:
If the input string begins with "0x" or "0X" (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be 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).
So the result depends on the browser if parsed input starts from '0'.
From the docs
If the radix is undefined, 0, or unspecified, JavaScript assumes the following:
- If the input string begins with "0x" or "0X" (a zero followed by lowercase or uppercase X), radix is assumed to be 16 and the rest of the string is parsed as a hexidecimal number.
- If the input string begins with "0" (a zero), radix is assumed to be 8 (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 clarifies that 10 (decimal) should be 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).
parseInt(string, radix);
string:
radix
From the ECMAScript® 2018 Language Specification (ECMA-262, 9th edition, June 2018):
If
radixisundefinedor0, it is assumed to be10except when the number begins with the code unit pairs0xor0X, in which case aradixof16is assumed. Ifradixis16, the number may also optionally begin with the code unit pairs0xor0X.
Specifically steps 6, 8 and 9 say:
6 - Let
Rbe ?ToInt32(radix).8 - If R ≠
0,...9 - Else
R=0, LetRbe10.
So when radix == 0, it will always be replaced with 10, assuming a compliant browser.
As per the documentation, if radix is undefined or 0, it is assumed to be 10. so,
parseInt('60', 10) = (0 * 10 ^ 0) + (6 * 10 ^ 1) = 60
and
parseInt('60', 0) = (0 * 10 ^ 0) + (6 * 10 ^ 1) = 60