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());
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.
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.
The toString() method returns a string representing the object. This method is meant to be overridden by derived objects for custom type conversion logic.
toString() Returns a string with each of the array values, separated by commas. Does not mutate the original array.
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()
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With