4

why in javascript 3.toString() throws exception and 3..toString() works fine? I saw it in a funny presentation about javascript but I cannot find the info WHY. Thank you in advance.

user2864740
  • 60,010
  • 15
  • 145
  • 220
homar
  • 575
  • 1
  • 7
  • 19

1 Answers1

10

Because a decimal point is a valid portion of a number, so the first dot is considered numeric, the second is for chaining.

If you'd prefer to avoid the double-period you could instead do:

(3).toString();

Or:

'' + 3;

Or:

String(3);
katspaugh
  • 17,449
  • 11
  • 66
  • 103
David Thomas
  • 249,100
  • 51
  • 377
  • 410