If I try to write
there is a syntax error. Using double dots, putting in a space, putting the three in parentheses or using bracket notation allows it to work properly.
3..toFixed(5) 3 .toFixed(5) (3).toFixed(5) 3["toFixed"](5)
Why doesn't the single dot notation work and which one of these alternatives should I use instead?
The period is part of the number, so the code will be interpreted the same as:
This will naturally give a syntax error, as you can't immediately follow the number with an identifier.
Any method that keeps the period from being interpreted as part of the number would work. I think that the clearest way is to put parentheses around the number:
2.toString(); // raises SyntaxError
As you mentioned, there are a couple of workarounds which can be used in order make number literals act as objects too. Any of these is equally valid.
2..toString(); // the second point is correctly recognized 2 .toString(); // note the space left to the dot (2).toString(); // 2 is evaluated first
3. as being either the start of a floating-point constant (such as
3.5) or else an entire floating-point constant (with
3. == 3.0), so you can't follow it by an identifier (in your case, a property-name). It fails to recognize that you intended the
3 and the
. to be two separate tokens.
Any of your workarounds looks fine to me.
3.e2 be interpreted as
a property e2 of 3? Therefore they voluntary decided to prefer
NumberLiterals here, just because there's actually not very much demand for things like
©2020 All rights reserved.