0
    14.toString();
    // Result -> SyntaxError: Unexpected token ILLEGAL

    14..toString();
    // Result -> "14"

What is placing an extra dot after the number doing, and how is this valid syntax?

contactmatt
  • 18,116
  • 40
  • 128
  • 186

2 Answers2

4

14. is a Number. .toString() calls a method on that Number.

Thus 14..toString() is the same as 14.0.toString().

You couldn't have 14.toString() because the . is still the floating point and not the property accessing symbol.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

It is important to remember that the parser is greedy.

It sees the 1, so it starts reading a number. 4 is valid in a number, . is valid in a number, t is not, so it stops.

So it has the number 14. (which is just 14). Now what to do with it? Uh... there's a t there, that's not valid, ERROR!


In the second case, . is valid in a number, . would be valid but we already have a dot so stop there.

We have 14. again, but this time when looking what to do it sees ., so it converts the 14. to a Number object, then calls toString() on it, result "14"


See also: Why does "a + + b" work, but "a++b" doesn't?

Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 1
    Of course, you should never be seeing this code "in real life". Just write `"14"` if it's a string that you want. – Niet the Dark Absol Jul 22 '14 at 15:25
  • I'm thinking pretty much the only valid use case would be calling `toLocaleString`: `1400000000..toLocaleString()` in my locale is `"1,400,000,000"` but for some other locales it would be `"1.400.000.000"`. – T.J. Crowder Jul 22 '14 at 15:39