I know 1 is not an object, but when I type 1..toString()
, it returns "1" in the console. Why is that?
Asked
Active
Viewed 501 times
-2

Paweł Łukasik
- 3,893
- 1
- 24
- 36

edison xue
- 1,291
- 2
- 16
- 21
-
It's a frequent question, let's look for the proper QA for closing... – Denys Séguret Jan 04 '17 at 16:18
-
@Loaf You should write this as an answer, not a comment. – bfontaine Jan 04 '17 at 16:19
-
This question has a lot of good explanations: http://stackoverflow.com/questions/4211037/what-is-the-double-dot-operator-in-javascript – Johnny Kutnowski Jan 04 '17 at 16:19
-
1..toString is not the double dot operator: http://stackoverflow.com/a/4211641/735926 – bfontaine Jan 04 '17 at 16:20
-
1`1 .toString()` is a fun alternative. – Dan Prince Jan 04 '17 at 16:20
-
1@Mouser Your comment is very very wrong – Denys Séguret Jan 04 '17 at 16:22
-
If the question is why you can access properties on primitive values, see [Does javascript autobox?](http://stackoverflow.com/q/17216847/218196) – Felix Kling Jan 04 '17 at 16:23
-
@Mouser - If that was true, you wouldn't be able to add numbers as it would do string concatenation. – Loaf Jan 04 '17 at 16:24
-
@DanPrince its fun and highly error prone – leoap Jan 04 '17 at 16:26
-
@leo_ap Anyone who writes `1 .toString()` rather than `'1'` deserves to have errors. – Dan Prince Jan 04 '17 at 16:28
-
@DanPrince I don't discuss that :) – leoap Jan 04 '17 at 16:40
3 Answers
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