How to Convert an Array to a String in JavaScript
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.
1 | const list = [1, 2, 3, 4]; |
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.
1 | const list = [1, 2, 3, 4]; |
We can pass a parameter to this method to add a custom separator:
1 | 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