Why does JavaScript treat a number as octal if it has a leading zero

var x = 010;
console.log(x); //8

The JS engine converts a number xto an octal number. Why it happens? How can I prevent this?

+11
source share
3 answers

I think my answer here answers the question, but the question is not exactly a duplicate, so I am enclosing a copy of my answer.

story

The problem is that decimal integer literals cannot 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 forbids doing this in strict mode:

(. 10.1.1) NumericLiteral OctalIntegerLiteral, B.1.1.

ECMAScript 6 BinaryIntegerLiteral OctalIntegerLiteral, :

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

OctalIntegerLiteral LegacyOctalIntegerLiteral, - .

, 8, 0o 0O ( ) parseInt.

, 10, parseInt.

  • 010
    • ( ECMAScript 5) .
    • 8 ( ).
  • 0o10, 0O10
    • ECMAScript 6 .
    • ECMAScript 6 8.
  • parseInt('010', 8)
    • 8.
  • parseInt('010', 10)
    • 10.
+8

, JavaScript- . ECMAScript.

- . ECMAScript:

(. 10.1.1), NumericLiteral, OctalIntegerLiteral, B.1.1.

- .

+2

JS treats numbers with leading zeros as octal, only if they are valid octal, if not, then it treats them as decimal. To prevent this, do not use leading zeros in the source code.

console.log(010, 10, +"010")

if (021 < 019) console.log('Paradox');
Run codeHide result

or use strict modenot to use leading zeros

'use strict'

if (021 < 019) console.log('Paradox');
Run codeHide result
0
source

All Articles