[ACCEPTED]-Number with leading zero in JavaScript-javascript

Accepted answer
Score: 20


It's being treated as octal (base 8) because 36 of the leading 0, just like a leading 0x would 35 make it hex (base 16). This has a long and 34 tortured history and is no longer how octal 33 numbers are written in modern JavaScript. In 32 modern JavaScript using strict mode, the 31 "legacy" octal format is a syntax 30 error; octal numbers are written with an 29 0o prefix.


Early on (in the initial language 28 from Netscape and the first and second ECMAScript 27 specifications), a leading 0 on a numeric 26 literal officially meant octal (base 8), just 25 as a leading 0x means hexadecimal (base 16):

OctalIntegerLiteral ::
    0 OctalDigit
    OctalIntegerLiteral OctalDigit

E.g., 10, 012, and 24 0xA were all ways of writing the decimal number 23 ten. This is in keeping with some other 22 languages with syntax similar to JavaScript 21 (C, C++, Java, ...), but it's highly confusing.

As 20 of ECMAScript 3, that form of octal 19 literal was downgraded to an optional extension, and 18 decimal integer literals were changed so 17 that they can't have leading zeros (unless 16 the implementation includes the extension):

DecimalIntegerLiteral ::
    NonZeroDigit DecimalDigits(opt)

But 15 ECMAScript 5 forbade doing that in strict-mode:

A conforming 14 implementation, when processing strict mode code (see 10.1.1), must not 13 extend the syntax of NumericLiteral to include OctalIntegerLiteral as described 12 in B.1.1.

ECMAScript 6 (ECMAScript 2015) introduces BinaryIntegerLiteral and OctalIntegerLiteral, so 11 now we have more coherent literals:

  • BinaryIntegerLiteral, prefixed with 0b or 0B.
  • OctalIntegerLiteral, prefixed with 0o or 0O.
  • HexIntegerLiteral, prefixed with 0x or 0X.

The old 10 OctalIntegerLiteral extension has been renamed to LegacyOctalIntegerLiteral, which is 9 still allowed in non-strict mode.


Therefore, if 8 you want to parse a number in base 8, use 7 the 0o or 0O prefixes (not supported by old 6 browsers), or use parseInt.

And if you want to be 5 sure your numbers will be parsed in base 4 10, remove leading zeros, or use parseInt.


  • 010
    • In strict mode (requires ECMAScript 5), it's a syntax error.
    • In non-strict mode, it may be a syntax error or return 8 (implementation dependent).
  • 0o10, 0O10
    • Before ECMAScript 6, they're syntax errors.
    • In ECMAScript 6, they return 8.
  • parseInt('010', 8)
    • It returns 8.
  • parseInt('010', 10)
    • It returns 10.

If you're 3 interested, you can find the current living 2 specification here, and historical versions 1 here.

Score: 18

With a leading zero, the number is interpreted 1 as octal and 4 * 8 = 32.

Score: 6

Because the 0 prefix indicates an octal number 1 (base 8).

More Related questions