Array.join()
The Array.join()
method is a great tool to have in your JavaScript toolbox. The .join()
method takes all of the items in an array and joins them together as a string, with the option for a separator between each array item.
Syntax
arr.join([separator]);
Joining An Array
Let's take a look at just a few of the different ways we can use the .join()
method. We will use .join()
without the optional separator argument, passing an empty string, using a space as the separator, and using a hyphen.
Omitting the separator argument
var arr = ['Welcome', 'to', 'Code', 'Snippet'];
arr.join(); // Notice how there is no argument passed as a separator
// returns "Welcome,to,Code,Snippet"
Try this the code snippet in your browser console.
Passing in an empty string as the separator
var arr = ['Welcome', 'to', 'Code', 'Snippet'];
arr.join(''); // Notice the empty string passed as the separator argument
// returns "WelcometoCodeSnippet"
Try this the code snippet in your browser console.
Separating items with a space
var arr = ['Welcome', 'to', 'Code', 'Snippet'];
arr.join(' '); // Notice the space (' ') passed as the separator argument
// returns "Welcome to Code Snippet"
Try this the code snippet in your browser console.
Separating items with a hyphen
var arr = ['Welcome', 'to', 'Code', 'Snippet'];
arr.join('-'); // Notice the hyphen passed as the separator argument
// returns "Welcome-to-Code-Snippet"
Try this the code snippet in your browser console.
If you'd like to take a closer look at how to use the .join()
method, checkout the Reverse a String blog post.
Shoot me an email at tim@timwheeler.com
with any questions and if you enjoyed this, stay tuned and subscribe below! 👇