HomeTutorsContact

How to convert array to a string in JavaScript?

By Gulshan Saini
Published in JavaScript
June 10, 2020
1 min read

We have couple of ways to converts JavaScript arrays to string.

Let’s say we have following array and we wan’t to convert the cars array to string.

const cars = ['Audi', 'BMW', 'MERC']

Converting array to comma separated string

First option is to use toString() on array. The toString() method will join the array items separated by comma and return a string representation of array.

cars.toString()

Output

"Audi,BMW,MERC"

Converting array to string separated by spaces

Another, way to convert array to string is to use the join() method. join() method works similar to toString() method however you can also specify separator while calling the method.

cars.join(' ')

Output

"Audi BMW MERC"

If you call the join() method on the array without specifying any separator it returns the same output as toString()

cars.join()

Output

"Audi,BMW,MERC"

Tip: If the array has only one item, then that item will be returned without using the separator.

Tip: The above method works well for nested arrays containing numbers and strings however, if you have an array of objects you might not get expected results and get output in [object Object] form.


Tags

#javascript
Previous Article
How to get viewport width and height using JavaScript?

Related Posts

JavaScript
How to check if a string contains a substring in JavaScript?
January 05, 2021
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Flutter
JavaScript
NextJS
ReactJS
Typescript

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media