Subscribe

JavaScript array join() method

✍️

JavaScript join method, how it works and why you need it

3 Dec, 2020 Β· 2 min read

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'

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'

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'

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';

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' ]

Now we can join this with a dash.

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

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next πŸ“–

Removing all vowels with JavaScript

3 Dec, 2022 Β· 2 min read

Removing all vowels with JavaScript

10 games to learn JavaScript

2 Dec, 2022 Β· 3 min read

10 games to learn JavaScript

Join 2097 devs and subscribe to my newsletter