How to convert an Array to a String in JavaScript
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
.
- JavaScript Array methods Splice vs Slice
- Difference between var, let and const in JavaScript
- How to convert a string to an integer in JavaScript
- How to use Map, Filter, and Reduce in JavaScript
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!