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
  • 17,508
  • 37
  • 123
  • 182

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
  • 857,932
  • 118
  • 1,152
  • 1,264
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
  • 311,322
  • 76
  • 447
  • 566