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"
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"
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()