JavaScript Array toString(): Get a String from an Array

The JavaScript toString() method is used to get a string from a specified array. The string contains its value as all elements of the specified array separated by commas. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="xyz"></p>

   <script>
      const myArray = ["Seattle", "Oakland", "Boston", "Austin", "Denver", "Berlin"];
      let myString = myArray.toString();
      document.getElementById("xyz").innerHTML = myString;
   </script>
   
</body>
</html>
Output

In the above example, the JavaScript code initializes an array myArray with six elements using the following statement:

const myArray = ["Seattle", "Oakland", "Boston", "Austin", "Denver", "Berlin"];

The toString() method is then called on myArray to convert it into a comma-separated string, which is then stored in the myString variable.

The document.getElementById() method is used to select the paragraph element with an id of "xyz." Finally, the innerHTML property of the selected paragraph element is set to the value of myString, which is the comma-separated string of the myArray elements.

JavaScript toString() syntax

The syntax of the toString() method in JavaScript is:

array.toString()

JavaScript toString() Example

Consider the following HTML and JavaScript code as another example demonstrating the "toString()" method in JavaScript:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>Value of <b>y</b> = <span id="a"></span></p>
   <p>Type of <b>y</b> = <span id="b"></span></p>

   <script>
      let x = ["Seattle", "Oakland", "Boston", "Austin", "Denver", "Berlin"];

      let y = x.toString();
      
      document.getElementById("a").innerHTML = y;
      document.getElementById("b").innerHTML = typeof(y);
   </script>
   
</body>
</html>
Output

Value of y =

Type of y =

JavaScript Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!