Clue Mediator

Convert an Array to String in JavaScript

📅January 4, 2020

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

Convert an Array to String in Javascript, JavaScript Array toString() Method, JavaScript Array join() Method, JavaScript: Convert Array to a String, Converting an Array to string, Javascript - Convert Array into Comma Separated String, Array.prototype.toString(), JavaScript | Array.join() Method.

Checkout more articles on JavaScript

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

Read more about Array Methods: Push, Pop, Shift and Unshift

Thank you for reading. Happy Coding!