-2

I know 1 is not an object, but when I type 1..toString(), it returns "1" in the console. Why is that?

enter image description here

Paweł Łukasik
  • 3,893
  • 1
  • 24
  • 36
edison xue
  • 1,291
  • 2
  • 16
  • 21

3 Answers3

6

Because the JavaScript parser assumes that 1. must be followed only by one or more digits to represent a float number. Using parentheses works: (1).toString().

bfontaine
  • 18,169
  • 13
  • 73
  • 107
1

Because it is interpreting 1. as the number. When you have 1.toString(), it is the same as saying (1.)toString(). Therefore 1..toString() is the same as (1.).toString()

Loaf
  • 3,011
  • 2
  • 15
  • 25
0

The reason why the below works is:

1..toString()

The 1.. is considered as a floating point number. The console expects something like:

1.0
1.5

Or something. If you are giving something like:

1.toString();

The above is not a valid number. That's the reason. So to make the above work, you need a parenthesis to tell that the number is completed:

(1).toString();
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252