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
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:
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)?
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.
- On arrays, the
join()method works just like
toString()except that it allows using a separator.
join()is an array method, so it only works on array objects.
toString()method works on every type of object, not just arrays.