Convert Array to a String in JavaScript

In this tutorial, we show you three ways to convert an array to a string in JavaScript.
  1. Using join() method
  2. Using toString() method
  3. Using an empty string
Check out all JavaScript examples at https://www.javaguides.net/p/javascript-tutorial-with-examples.html

1. Using join() method

The join() method converts the array of elements into a string separated by the commas.
Example 1:
const strArry = ['r','a','m', 'e', 's', 'h'];
console.log(strArry.join());
Output:
r,a,m,e,s,h
Example 2:
const arr = ['r','a','m', 'e', 's', 'h', 1,2,3];
console.log(arr.join());
Output:
r,a,m,e,s,h,1,2,3
We can also pass our own separator as an argument to the join() method.
In this below example, we passed - as a separator argument so that string is separated by a minus operator -.
Example:
const arr = ['r','a','m', 'e', 's', 'h', 1,2,3];
console.log(arr.join('-'));
Output:
r-a-m-e-s-h-1-2-3

2. Using toString() method

The toString() method also joins the array and returns the string where the array of elements is separated by the commas.
Example:
const strArry = ['r','a','m', 'e', 's', 'h'];
console.log(strArry.toString());
Output:
r,a,m,e,s,h


3. Using an empty string

If we add an array with an empty string '' it converts the array to a string.
Example:
const strArry = ['r','a','m', 'e', 's', 'h'];

console.log(strArry + '');
Output:
r,a,m,e,s,h

Comments