I'm trying to understand why you would ever use toString() on a string.
tutorialspoint.com gives this example.
<html>
<head>
<title>JavaScript String toString() Method</title>
</head>
<body>
<script type="text/javascript">
var str = "Apples are round, and Apples are Juicy.";
document.write(str.toString( ));
</script>
</body>
</html>
Why not just use
document.write(str);
toString()
method doesn't make any practical sense when called on a "pure" sring, like "Apples are round, and Apples are Juicy."
.
It may be useful when you need to get the string representation of some non-string value.
// Example:
var x = new String(1000); // converting number into a String object
console.log(typeof x); // object
console.log(typeof x.toString()); // string
console.log(x.toString()); // "1000"
The String object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For String objects, the toString() method returns a string representation of the object and is the same as the String.prototype.valueOf() method.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toString
Even if you don't use the toString
function, it is invoked (implicitly) to get the value that is used for the document.write()
function.
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