6.10 Joining an Array
Another useful method for arrays is the join method. So here we have this array of numbers, let's say we want to join the elements of this array. This is when we use the join method. So we call numbers. Join now look at this parameter here, seperator with a ? Whenever you see a question mark, it means that this parameter is optional, and you can see that this type of parameter is a string, so here we can optionally pass a string and that string will be used separately. So let's say we want to join these elements using a comma. So we pass a comma as a string here. And notice that this join method returns a string. So we get the result and store it in a constant called joined. Now let's do a console log of join. Save the changes and here is the result. Another useful method that goes along with join is the split method, but this method is not part. of arrays, it's part of strings, let me show you how this works. So let's say we have a string called message like this. This is my first message. Now we can split the sentence like this. So message. Split, again here we have to pass the split string so let's say we want to split this using a white space. This method will return an array, so we're going to call a constant share, now let's look at this array on the console. So here's the array, we have five elements here, each element in this array is a word in our original message. Now that we have an array, we can use the join method, to combine these elements using a separator. So, we do a part. join, you can combine them using a hyphen, and store the result in a constant that we'll call combined and finally connect it to the console. So here is the result. This is my first message. This technique is particularly useful when creating a URL slug. Let me show you what I mean by that. So, here I have this page open stackoverflowcom. We have this title: "Creating arrays in Javascript". So this is what the user posted, as you can see, we have a white space between each word, but we can't have white space in URLs. So if you look at this URL here, the title is converted to a URL slug. So all the white space is replaced with a dash. So as part of the title to url slug conversion, you'll need to split this string, maybe delete some words, replace some words with other words, and then combine them using the hyphen as you can see here. That's it for this video on the Join method in JavaScript, let's meet again for a very next video.