Reputation: 1323
How come this works:
var num = 1;
console.log(num.toString()); // "1"
But this does not?
console.log(1.toString()); // SyntaxError: Unexpected token ILLEGAL
Upvotes: 2
Views: 123
Reputation: 166021
Because the grammar expects a .
after a number to be parsed as part of that number, as it would be for e.g. 1.5
. You need to disambiguate the .
if you want to use it as a member operator on a numeric literal:
1..toString(); // "1"
1.0.toString(); // "1"
(1).toString(); // "1"
In the first two cases the first .
is parsed as a floating point. The second can only be parsed as a member operator because numeric literals can only contain a single floating point.
This is shown by the NumericLiteral grammar in the spec.
Upvotes: 8