How to Convert an Array to a String in JavaScript ?
In JavaScript, you can convert an array to a string using the join()
method or by using the toString()
method. Both methods provide different ways to concatenate the elements of an array into a single string.
Using join()
method: The join()
method joins all elements of an array into a string, using a specified separator between each element.
Javascript
let myArray = [1, 2, 3, 4, 5]; // Convert the array to a string using join() let arrayString = myArray.join( ', ' ); console.log(arrayString); // Output: "1, 2, 3, 4, 5" |
Output
1, 2, 3, 4, 5
Using toString()
method: The JavaScript Number toString() method in Javascript is used with a number and converts the number to a string. It is used to return a string representing the specified Number object.
Javascript
let myArray = [1, 2, 3, 4, 5]; // Convert the array to a string using toString() let arrayString = myArray.toString(); console.log(arrayString); // Output: "1,2,3,4,5" |
Output
1,2,3,4,5