JavaScript join
function is built in to every JS Array. It’s very useful to join the elements of the JavaScript array and convert it into a string.
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.
apple,orange,banana
How to use a custom separator with join
To use a custom separator with Array.join
in JS, you should just pass it as an argument into join()
.
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.
London-Paris-Tokyo
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:
1cool2cool3
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!