boxtrain
boxtrain

Reputation: 2578

Strange octal behavior

From what I understand, octal literals (of the form 023) are not valid in ECMAScript 5, but are widely supported. In ECMAScript 6, they are newly supported in the format 0o23 or 0O23. What confuses me is the behavior of numbers that are not valid octal numbers, but have a preceding zero (019). These seem to behave as normal, decimal numbers.

So without strict mode, I can get things like 022 === 018 (true), because 022 is interpreted as octal, and presumably 018 is treated as decimal since it can't be octal.

In strict mode, I get an error when using a valid octal number in that format (eg 022), but not when using a zero-prefixed number that can't be a valid octal number (eg 018).

This seems very odd to me, like JS (strict-mode) is telling me that I can put a 0 in front of my number, as long as it is an INVALID octal. In ES6 (or later), will zero-prefixed numbers (possible octals or otherwise) be invalid, or treated as decimals?

Upvotes: 3

Views: 158

Answers (1)

hindmost
hindmost

Reputation: 7195

This is a documented feature:

Decimal literals can start with a zero (0) followed by another decimal digit, but If all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number. This won't throw in JavaScript.

If you want to force treating a number as octal you can use new literal form 0o (or 0O) introduced in ES6.

Upvotes: 3

Related Questions