Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a method like `toString` require two dots after a number? [duplicate]

Tags:

javascript

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());
like image 656
Atul Sharma Avatar asked May 15 '17 10:05

Atul Sharma


People also ask

What does toString() do in JavaScript?

The toString() method returns a string as a string. The toString() method does not change the original string. The toString() method can be used to convert a string object into a string.

What is number toString?

toString() . For Number values, the toString method returns a string representation of the value in the specified radix. For radixes above 10, the letters of the alphabet indicate digits greater than 9. For example, for hexadecimal numbers (base 16) a through f are used.

What is toString in react?

The toString() method returns a string representing the object. This method is meant to be overridden by derived objects for custom type conversion logic.

Does toString mutate js?

toString() Returns a string with each of the array values, separated by commas. Does not mutate the original array.


2 Answers

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().

like image 198
Karl-Johan Sjögren Avatar answered Nov 13 '22 21:11

Karl-Johan Sjögren


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

like image 40
Vivek Nerle Avatar answered Nov 13 '22 21:11

Vivek Nerle