Javascript parseInt() with leading zeros

This is because if a number starts with a '0', it's treated as base 8 (octal).

You can force the base by passing the base as the 2nd parameter.

parseInt("09", 10) // 9

According to the docs, the 2nd parameter is optional, but it's not always assumed to be 10, as you can see from your example.


Calls to parseInt should always specify a base in the second argument:

parseInt("08", 10);

Earlier versions of JavaScript treat strings starting with 0 as octal (when no base is specified) and neither 08 nor 09 are valid octal numbers.

From the Mozilla documentation:

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.

And from the ECMAScript 3 standard:

When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X, then the implementation may, at its discretion, interpret the number either as being octal or as being decimal. Implementations are encouraged to interpret numbers in this case as being decimal.

The latest version of JavaScript (ECMAScript 5) abandons this behavior, but you should still specify the radix to satisfy older browsers.