TL DR
It is considered octal (base 8) because of the leading 0 , just as the leading 0x will make it hexadecimal (base 16). It has a long and tortured history, and is no longer the way octal numbers are written in modern JavaScript. In modern JavaScript using strict mode, the octal eight-digit format is a syntax error; octal numbers are prefixed with 0o .
History
At the beginning (in the source language from Netscape and the first and second ECMAScript specifications), the leading 0 in the numeric literal officially meant octal (base 8), just as the leading 0x means hexadecimal (base 16):
OctalIntegerLiteral :: 0 OctalDigit OctalIntegerLiteral OctalDigit
For example, 10 , 012 and 0xA were all ways of writing the decimal number ten. This corresponds to some other languages ββwith syntax similar to JavaScript (C, C ++, Java, ...), but it is very confusing.
As with ECMAScript 3, this form of the octal literal has been reduced to an additional extension, and decimal integer literals have been changed so that they cannot have leading zeros (unless the implementation includes the extension):
DecimalIntegerLiteral :: 0 NonZeroDigit DecimalDigits(opt)
But ECMAScript 5 forbade doing this in strict mode:
The corresponding implementation when processing strict code mode (see 10.1.1) should not extend the NumericLiteral syntax to include OctalIntegerLiteral, as described in B.1.1 .
ECMAScript 6 (ECMAScript 2015) introduces BinaryIntegerLiteral and OctalIntegerLiteral, so now we have more consistent literals:
- BinaryIntegerLiteral, prefixed with
0b or 0b . - OctalIntegerLiteral, prefixed with
0o or 0o . - HexIntegerLiteral prefixed with
0x or 0x .
The old OctalIntegerLiteral extension has been renamed LegacyOctalIntegerLiteral, which is still allowed in lax mode.
Conclusion
Therefore, if you want to parse a number in base 8, use the 0o or 0o prefixes (not supported by older browsers) or use parseInt .
And if you want to make sure that your numbers will be analyzed in base 10, remove the leading zeros or use parseInt .
<strong> Examples
010- In strict mode (ECMAScript 5 required), this is a syntax error.
- In lax mode, this may be a syntax error or a return of
8 (implementation dependent).
0o10 , 0o10- Before ECMAScript 6, they are syntax errors.
- In ECMAScript 6, they return
8 .
parseInt('010', 8)parseInt('010', 10)
If you're interested, you can find the current current specification here and historical versions here .