JavaScript Array.toString() Method

Sneha Lodha Jan 30, 2023
  1. Syntax of JavaScript array.toString() Method
  2. Example Codes: Use of array.toString() to Convert an Array Into a String
  3. Example Codes: Use of array.toString() With array.slice() Method to Create a String by Removing Some Elements
JavaScript Array.toString() Method

In JavaScript, the array.toString() method can convert a whole array into a string that will be separated by commas. While creating a string using this method, we can also use the array.slice() method to slice the array and convert the remaining array elements to the string.

Syntax of JavaScript array.toString() Method

refarray.toString();
refarray.slice.toString();

Return

This method returns a string containing an array’s elements separated by commas.

Example Codes: Use of array.toString() to Convert an Array Into a String

const array = ['JavaScript', 'Python', 'C++'];
let string = array.toString();
console.log(string);

Output:

JavaScript,Python,C++

The above code will return a string containing an array’s elements separated by commas.

Example Codes: Use of array.toString() With array.slice() Method to Create a String by Removing Some Elements

const array = ["Converting", "Array", "into", "String"];
let str = array.slice(1).toString();
console.log(str);

Output:

Array,into,String

This code will return the string of the array elements that were not removed by the array.slice() method.

We can use the array.join(separator) method with array.toString() to remove commas while creating a string.

Related Article - JavaScript Array