In JavaScript, you can convert an array into a string using the toString()
method or the join()
method. Let’s explore both methods.
Using the toString()
Method
The toString()
method can be used to convert an array to a string representation. This method returns a string that consists of the array elements separated by commas.
const list = [1, 2, 3, 4];
list.toString();
Example:
Using the join()
Method
The join()
method returns a string that is the result of concatenating all the elements of an array. By default, the elements are joined together with commas. However, you can pass a parameter to specify a custom separator.
const list = [1, 2, 3, 4];
list.join();
We can pass a parameter to this method to add a custom separator:
list.join(', ');
Example:
By using either the toString()
or join()
method, you can easily convert an array to a string in JavaScript.
Tags: JavaScript, Array, String, Conversion