-2

For some reason, when I try to call toString on a literal number, it fails:

> 5.toString()
SyntaxError: Unexpected token ILLEGAL

So I tried putting it in a variable, and it worked:

> var five = 5
undefined
> five.toString()
"5"

I thought that was a bit strange, and after some more experimenting, I found out that wrapping a literal in parenthesis somehow makes it work:

> (5).toString()
"5"

That seemed very strange! Why would wrapping the literal in parenthesis change anything? Why does 5.toString() not work?

tckmn
  • 57,719
  • 27
  • 114
  • 156

2 Answers2

8

The dot . after the number represents a decimal point.

It would work if you do;

5..toString();

To clarify when a decimal point is followed by a number in javascript it expects the next character to be that of a number, so if toString() is there instead it is considered an illegal token as t is not a valid number.

This is another valid way of doing the same thing but is easier to read and follow;

5.0.toString();
GriffLab
  • 2,076
  • 3
  • 20
  • 21
2

Why would wrapping the literal in parenthesis change anything?

This causes the literal to become an expression. As a result, you can call the method .toString() on the expression. As linked by @Musa, the . after a number is interpreted as a decimal point causing an exception to be thrown when 5.t is encountered as t is not a valid number.

Travis J
  • 81,153
  • 41
  • 202
  • 273