Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

According to the ECMAScript spec the integer part of a decimal number should be

ID: 646874 • Letter: A

Question

According to the ECMAScript spec the integer part of a decimal number should be either zero or start with a non-zero digit. A hexadecimal value should start with 0x.

Javascript, in the major browsers, extends EMCAScript to include octal numbers. These are determined by having a sequence of digits (from 0 to 7 inclusive) start with a zero.

Given these facts, my naive implementation of a javascript interpreter would probably parse integers a bit like this:

if first_char in [1-9] then
    parse_input_as_decimal()
else if first_char is 0 then
    if second_char is 'x' then
        parse_input_as_hexadecimal()
    else if second_char in [1-7] then
        parse_input_as_octal()
    else
        parse_input_as_zero()
However the web browsers seem to act slightly weird in that if a number beginning with zero contains the digits 8 or 9 then it reads it as a valid decimal. This can lead to oddities, especially when using a decimal point or exponent. Some examples:

011 // is octal
0011 // is octal
019 // is decimal
0091 // is decimal
011.0 // throws an error
019.0 // is decimal
011e5 // throws an error
019e5 // is decimal
My question is why do they behave like this? Is it just some quirk of history? Or is there a good reason? Is it written in some spec somewhere? Will this ever change?

I know this is a bit arcane and few people use octals in javascript these days, but I'm curious.

Explanation / Answer

Quirk:'strict mode' gets rid of this behavior, I think it was a non standard behavior that a couple browsers implemented but I'm not 100% (about it being non-standard, I am sure about it being removed from strict JavaScript)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote