var x = 010; console.log(x); //8
JS engine convert the number
x to octal number. Why it happens? How can I prevent it?
However, in strict mode, the conforming implementations must not implement that - see ECMAScript specification again:
A conforming implementation, when processing strict mode code (see 10.1.1), must not extend the syntax of NumericLiteral to include OctalIntegerLiteral as described in B.1.1.
Because of this ambiguity, it's better not to use leading zeros.
JS treat numbers with leading zeros as octal only if they valid octal, if not then it treat it as decimal. To prevent this not use leading zeros in your source code
console.log(010, 10, +"010") if (021 < 019) console.log('Paradox');
strict mode to not allow using leading zeros
'use strict' if (021 < 019) console.log('Paradox');
I think my answer here answers the question, but the question is not exactly a duplicate, so I include a copy of my answer.
The problem is that decimal integer literals can't have leading zeros:
DecimalIntegerLiteral :: 0 NonZeroDigit DecimalDigits(opt)
However, ECMAScript 3 allowed (as an optional extension) to parse literals with leading zeros in base 8:
OctalIntegerLiteral :: 0 OctalDigit OctalIntegerLiteral OctalDigit
But ECMAScript 5 forbade doing that in strict-mode:
ECMAScript 6 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
©2020 All rights reserved.