JavaScript array join() method

β€” 3 minute read

permalink

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 permalink

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 permalink

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! permalink

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