Why does 42.toString () fail in JS?

Renouncement

Guys, I'm DO aware of Why 10..toString () works, but 10.toString () is not responding? but the fact is that it does not provide a formal explanation.

Interpretation of the specification. the symbol in this particular position is that it will be decimal. This is determined by the syntax of the ECMAScript numeric literal.

Not referenced to standard

Question body

I subconsciously understand that

42..toString() 

handled by the parser as the number 42. followed by a call to .toString() .

I do not understand why the interpreter cannot understand that

 42.toString() 

is 42 , followed by a method call.

Is this just a flaw in modern JS interpreters or is it explicitly stated by ES5.1?

From ES5.1, a Numeric Literal is defined as (only a significant part of the definition):

 NumericLiteral :: DecimalLiteral HexIntegerLiteral DecimalLiteral :: DecimalIntegerLiteral . DecimalDigits(opt) ExponentPart(opt) . DecimalDigits ExponentPart(opt) DecimalIntegerLiteral ExponentPart(opt) 

The last rule is what I expect to choose with a parser.

UPD : to clarify, this question expects as an answer references to the ES specification, which explicitly indicate that the interpreter should behave as if it

+6
source share
2 answers

I believe the part you are missing is this quote from section 7 :

The source text is scanned from left to right, repeating the maximum possible sequence of characters as the next input element.

Pay attention to the "maximum possible sequence of characters"; since "42". - This is a valid token (which is a kind of input element), it should be used instead of "42", and then ".".

+8
source

The lexical phase of the parsing process consumes . it is because of the definition of NumericLiteral specified in the standard. The definition indicates that a numerical literal (here a DecimalLiteral ) includes . if there is one, see the first line under DecimalLiteral :: .

Since 42. consumed by a numeric literal token, the next toString token, which does not have an initial period and therefore cannot be recognized as a method call.

0
source

Source: https://habr.com/ru/post/971314/


All Articles