var num = 040; console.log(num); // 32
Since when is 40 = 32?
With a leading zero, the number is interpreted as octal and
4 * 8 = 32.
It's being treated as octal (base 8) because of the leading
0, just like a leading
Early on (in the initial language from Netscape and the first and second ECMAScript specifications), a leading
0 on a numeric literal officially meant octal (base 8), just as a leading
0x means hexadecimal (base 16):
OctalIntegerLiteral :: 0 OctalDigit OctalIntegerLiteral OctalDigit
As of ECMAScript 3, that form of octal literal was downgraded to an optional extension, and decimal integer literals were changed so that they can't have leading zeros (unless the implementation includes the extension):
DecimalIntegerLiteral :: 0 NonZeroDigit DecimalDigits(opt)
But ECMAScript 5 forbade doing that in strict-mode:
ECMAScript 6 (ECMAScript 2015) introduces BinaryIntegerLiteral and OctalIntegerLiteral, so now we have more coherent literals:
The old OctalIntegerLiteral extension has been renamed to LegacyOctalIntegerLiteral, which is still allowed in non-strict mode.
Therefore, if you want to parse a number in base 8, use the
0O prefixes (not supported by old browsers), or use
And if you want to be sure your numbers will be parsed in base 10, remove leading zeros, or use
0 prefix indicates an octal number (base 8).
©2020 All rights reserved.