Learn how to convert an array into a string with JavaScript, by using two different methods.
JavaScript has a couple of methods that allow you to return array content as a string. They’re called toString()
and join()
. On the surface, they appear almost identical, but as you shall see, they’re not. Let’s test them both!
Here’s an array object with a list of numbers:
const numbersArray = [2, 4, 6, 8, 10]
To convert the array to a string, let’s try to attach the toString()
method to numbersArray
:
const numbersArray = [2, 4, 6, 8, 10]
numbersArray.toString()
Now try to print out the result:
console.log(numbersArray.toString())
// String: "2,4,6,8,10"
As you can see, toString()
indeed converted the numeric array into a single string value that looks like this:
"2,4,6,8,10"
But wait, all the spaces after the commas were removed in the process. What if you need space separation between words (e.g. to allow word or line wrapping)?
Fortunately, we can use JavaScript’s join()
method to do that by passing a separator inside it as an argument, like this:
const numbersArray = [2, 4, 6, 8, 10]
numbersArray.join(", ")
Now try to print the result:
console.log(numbersArray.join(", "))
// "2, 4, 6, 8, 10"
Nice, that looks much better, presentation-wise, and will allow word/line wrapping in case you need it.
join() vs. toString() - good to know:
- On arrays, the
join()
method works just liketoString()
except that it allows using a separator. join()
is an array method, so it only works on array objects.- The
toString()
method works on every type of object, not just arrays.