Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you use string.toString()?

Tags:

javascript

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);
like image 741
user1757006 Avatar asked Dec 14 '22 05:12

user1757006


2 Answers

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

like image 103
RomanPerekhrest Avatar answered Jan 13 '23 12:01

RomanPerekhrest


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.

like image 44
Joe Antony Avatar answered Jan 13 '23 13:01

Joe Antony