11

What is the logic behind 42..toString() with ..?

The double dot works and returns the string "42", whereas 42.toString() with a single dot fails.

Similarly, 42...toString() with three dots also fails.

Can anyone explain this behavior?

console.log(42..toString());

console.log(42.toString());
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65

3 Answers3

12

When you enter 42.toString() it will be parsed as 42 with decimal value "toString()" which is of course illegal. 42..toString() is simply a short version of 42.0.toString() which is fine. To get the first one to work you can simply put paranthesis around it (42).toString().

Karl-Johan Sjögren
  • 16,544
  • 7
  • 59
  • 68
2

it is like 42.0.tostring() so it show's decimal point you can use (42).toString() 42 .toString() that also work there is space between 42 and dot. This is all because in javascript almost everything is object so that confusion in dot opt.

Afzal Patel
  • 124
  • 1
  • 6
1

With just 42.toString(); it's trying to parse as a number with a decimal, and it fails.

and when we write 42..toString(); taken as 42.0.toString();

we can get correct output by

(42).toString();

(42.).toString();

Can refer Link for .toString() usage

Vivek Nerle
  • 304
  • 2
  • 14