3

Can someone explain in detail what is going on here? Specifically the double dot notation.

(3.14).toFixed(); // "3"
3.14.toFixed(); // "3"

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

source

1

2 Answers 2

9

According to ECMA Script 5.1 Specifications, grammar for decimal literals are defined like this

DecimalLiteral ::

   DecimalIntegerLiteral . [DecimalDigits] [ExponentPart]

   . DecimalDigits [ExponentPart]

   DecimalIntegerLiteral [ExponentPart]

Note: The square brackets are just to indicate that the parts are optional.

So, when you say

3.toFixed()

After consuming 3., the parser thinks that the current token is a part of a Decimal Literal, but it can only be followed by DecimalDigits or ExponentPart. But it finds t, which is not valid, that is why it fails with SyntaxError.

when you do

3..toFixed()

After consuming 3., it sees . which is called property accessor operator. So, it omits the optional DecimalDigits and ExponentPart and constructs a Floating point object and proceeds to invoke toFixed() method.

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

3 .toFixed()
Sign up to request clarification or add additional context in comments.

Comments

8

3. is a number, so the . is the decimal point and doesn't start a property.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.