Convert Array to String with Spaces in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 20 20211 min read

banner

Photo by Joshua Earle

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 your use case requires 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(' ')); // ๐Ÿ‘‰๏ธ ''

Note that 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'

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

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee