Convert Array to String with Spaces in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Convert Array to String with Spaces in JavaScript #

To convert an array to a string with spaces, call the join() method on the array, passing it a string containing a space as a parameter - arr.join(' '). The join method returns a string with all array elements joined by the provided separator.

index.js
const arr = ['a', 'b', 'c']; const withSpaces = arr.join(' '); console.log(withSpaces); // 👉️ 'a b c' console.log(typeof withSpaces); // 👉️ string

The only parameter the Array.join method takes is a separator.

The method returns a string containing all array elements joined by the provided separator.

If the separator is a string containing a space, then all array elements get joined by a space.

If you need to convert the array into a string with a different separator, pass the character(s) as a parameter to the join() method.

index.js
const arr = ['a', 'b', 'c']; const withSpaceAndComma = arr.join(', '); console.log(withSpaceAndComma); // 👉️ 'a, b, c' const withHyphens = arr.join('-'); console.log(withHyphens); // 👉️ 'a-b-c' const withoutSeparator = arr.join(''); console.log(withoutSeparator); // 👉️ 'abc'

If the join method gets called on an empty array, it returns an empty string.

index.js
console.log([].join(' ')); // 👉️ ''

If the array on which the join method is called contains elements that are null, undefined of empty array [], they get converted to an empty string.

index.js
const arr = ['a', undefined, 'c']; console.log(arr.join(' ')); // 👉️ 'a c'

Our array contains an element with a value of undefined, so it got converted to an empty string.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.