JavaScript provides two methods using which you can convert an array to a string:
The toString()
method returns a string representation of an array. Within that string, array elements are separated by commas.
Note: The toString()
method does not modify the original array.
let numbers = [1, 2, 3, 4, 5]; numbers.toString(); //"1,2,3,4,5"
If you want to convert array to string but don't want commas within the generated string, use the join()
method.
Array join()
method accepts a string parameter that works as a separator and returns a string with array values separated by the provided separator.
let numbers = [1, 2, 3, 4, 5]; numbers.join(" "); //"1 2 3 4 5" numbers.join("-"); //"1-2-3-4-5"
If you don't pass a separator to the join()
method, it will use commas as the separator.
numbers.join(); //"1,2,3,4,5"
On the other hand, if you pass an empty string to the join()
method, it will simply combine all the array elements.
numbers.join(""); //"12345"
Note: The join()
method does not modify the original array.
If you use toString()
and join()
methods with an array of objects, you will get [object Object]
. So, to convert an array of objects to a string, you must use JSON.stringify()
method.
let inventory = [ { name:'Google Nest Cam Indoor', quantity:10 }, { name:'Amazon Blink Mini', quantity:22 }, { name:'Ring Video Doorbell', quantity:5 } ]; console.log(inventory.toString()); console.log(inventory.join()); console.log(JSON.stringify(inventory));
Output
[object Object],[object Object],[object Object] [object Object],[object Object],[object Object] [{"name":"Google Nest Cam Indoor","quantity":10},{"name":"Amazon Blink Mini","quantity":22},{"name":"Ring Video Doorbell","quantity":5}]"