Here’s the basic syntax:
const fruits = ['apple', 'orange', 'banana']; const joinedFruits = fruits.join(); console.log(joinedFruits);
As you see, we’ve called
.join() without any arguments which returned a string that consists of all the array elements separated by commas.
How to use a custom separator with
To use a custom separator with
Array.join in JS, you should just pass it as an argument into
Let’s try use dashes this time.
const cities = ['London', 'Paris', 'Tokyo']; const joinedCities = cities.join('-'); console.log(joinedCities);
As a result we’ll still get a string, but the array elements will be split (or joined) with dashes instead of commas.
How to use a long separator to concatenate a JS array
You’re not limited in the length of the separator that you want to use.
For example, you can use the word
cool instead of commas or dashes.
const numbers = [1, 2, 3]; const joinedNumbers = numbers.join('cool'); console.log(joinedNumbers);
Here’s the output: