Convert an Array to String in JavaScript
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()
The join()
method is an in-built function in JavaScript which converts the array of elements into a string separated by commas.
Syntax:
1 | 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 (,
).
1 2 3 4 5 6 | 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:
1 | arr.toString() |
Let’s take an example to convert an array to a string using toString() method.
1 2 3 | 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.
1 2 3 4 5 6 7 8 9 10 | 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!