What is this javascript syntax?

Can someone explain in detail what is happening here? In particular, the designation with a double point.

(3.14).toFixed(); // "3" 3.14.toFixed(); // "3" (3).toFixed(); // "3" 3.toFixed(); // SyntaxError: Unexpected token ILLEGAL 3..toFixed(); // "3" 

a source

+5
source share
2 answers

According to ECMA Script 5.1 Technical Specifications , the grammar for decimal letters is defined as follows

 DecimalLiteral :: DecimalIntegerLiteral . [DecimalDigits] [ExponentPart] . DecimalDigits [ExponentPart] DecimalIntegerLiteral [ExponentPart] 

Note: The square brackets are intended only to indicate that parts are optional.

So when you say

 3.toFixed() 

After using 3. , the parser considers that the current token is part of the decimal literal, but only DecimalDigits or ExponentPart can follow it. But it finds t , which is invalid, so it does not work with SyntaxError.

when you do

 3..toFixed() 

After using 3. he sees . called the property access operator. Thus, it omits the optional DecimalDigits and ExponentPart and builds a floating-point object and proceeds to call the toFixed() method.

One way to overcome this is to leave a space after the number, for example

 3 .toFixed() 
+9
source

3. is a number, therefore . is a decimal point and does not start the property.

3..something is a number followed by a property.

+8
source

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


All Articles