• Post category:JavaScript
  • Reading time:4 mins read

In this article, we will let you know about how to convert an array to a string in JavaScript. There are multiple ways to convert an array to string but we will consider three major methods join(), toString() and Loop.

Way to convert an array to string

  1. join()
  2. toString()
  3. Loop

1. join()

The join() method is an in-built function in JavaScript which converts the array of elements into a string separated by commas.

Syntax:

arr.join()  OR  arr.join(separator)

As mentioned in syntax, we can pass separator as an argument to this method. The default separator is a comma (,).

var flowers = ['Rose', 'Lotus','Sunflower','Marigold'];
var newArray = flowers.join();
console.log(newArray); // Output: Rose,Lotus,Sunflower,Marigold

var newArray = flowers.join(' - ');
console.log(newArray); // Output: Rose - Lotus - Sunflower - Marigold

2. toString()

The toString() method also joins the array and returns a comma separated value. Its default separator is the comma (,) and it doesn’t allow to specify separator.

Syntax:

arr.toString()

Let’s take an example to convert an array to a string using toString() method.

var flowers = ['Rose', 'Lotus','Sunflower','Marigold'];
var newArray = flowers.toString();
console.log(newArray); // Output: Rose,Lotus,Sunflower,Marigold

3. Loop

If in some of the case, we can’t use in-built method then we can loop through the array and convert it to a string manually.

var numbers = [28,17,45,90,67,23];
var length = numbers.length;  // find an array length
var str = ‘’;
for(var i=0; i< length; i++) {
  str += numbers[i];  // concat Array value to a string variable
  if(i < (length-1) ){
    str += ',';  // add separator
  }
}
console.log(str); // Output: 28,17,45,90,67,23

Thank you for reading. Happy Coding!

Leave a Reply