DEV Community

Cover image for JavaScript array join() method
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

JavaScript array join() method

Another Array method, and this time the join() method, we have seen this in use in yesterdays four-digit pincode.

What it does is it combines an array with a delimiter you specify.

Using the Javascript join() method

In the most basic example let's convert this array into a string.

const input = ['Hello', 'world', 'how', 'are', 'you'];
const output = input.join(' ');
// 'Hello world how are you'
Enter fullscreen mode Exit fullscreen mode

In this example we used a empty string to join the words, we can use anything really:

const input = ['Hello', 'world', 'how', 'are', 'you'];
const output = input.join('๐Ÿ‘€');
// 'Hello๐Ÿ‘€world๐Ÿ‘€how๐Ÿ‘€are๐Ÿ‘€you'
Enter fullscreen mode Exit fullscreen mode

It can only take one argument which is the separator. This is a optional parameter, if we leave it empty we get the following result:

const input = ['Hello', 'world', 'how', 'are', 'you'];
const output = input.join();
// 'Hello,world,how,are,you'
Enter fullscreen mode Exit fullscreen mode

Real-world example

An example where one would use this, is of course, like in the four-digit JavaScript input.

But another really good one is converting titles into slugs.
A slug would be a URL friendly version of your title.

Let's say we have the following title.

const title = 'this is my article title';
Enter fullscreen mode Exit fullscreen mode

Notice how this is not an array, so how can we join this into a slug?

First let's split it on each space:

const output = title.split(' ');
// [ 'this', 'is', 'my', 'article', 'title' ]
Enter fullscreen mode Exit fullscreen mode

Now we can join this with a dash.

const output = title.split(' ').join('-');
// 'this-is-my-article-title'
Enter fullscreen mode Exit fullscreen mode

There you go!
Super awesome function and very useful!

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)