• JavaScript Video Tutorials

JavaScript - Array toString() Method



The JavaScript Array.toString() method is used to convert an array to a string by concatenating every element of a array with a comma between them. In other words, this method returns the string representation of the array elements.

For instance, if we consider an array [11,22,33], the toString() method would result in the string “11,22,33”. Array elements such as "undefined", "null", or "empty array", have an empty string representation. This method doesn’t modify the original array.

Syntax

Following is the syntax of JavaScript Array toString() method −

array.toString();

Parameters

This method does not accept any parameters.

Return value

This method returns a string representing the elements of an array, separated by commas.

Examples

Example 1

In this example, the toString() method is called on the string array, and it returns a string where the array elements are joined with commas.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Cheetah", "Tiger", "Elephant", "Dinosaur"];
      let result = animals.toString();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

As we can see the output, it returned a string with all the array elements.

Lion,Cheetah,Tiger,Elephant,Dinosaur

Example 2

Here, the toString() method is used on the numbers array, converting it to a string where each number is separated by a comma.

<html>
<body>
   <p id="demo"></p>
   <script>
      const numbers = [1, 2, 3, 4, 5, 6];
      let result = numbers.toString();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

As we can see the output, it returned a string with all the number array elements.

1,2,3,4,5,6

Example 3

Here, we are recursively converting each element of the array and also nested array elements into a string.

<html>
<body>
   <p id="demo"></p>
   <script>
      const MatrixArray = [
         [10, 20, 30],
         [40, 50, 60],
         [70, 80, 90],
      ];
      let result = MatrixArray.toString();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

After executing the above program, the nested array will be flattened and returns as a string.

Output

10,20,30,40,50,60,70,80,90
Advertisements