Hi Friends 👋,

Welcome To Infinitbility! ❤️

Today, we are going to learn how can we convert arrays which have store strings to comma (,) separated strings, here we will use the javascript join method to do this.

Table of content

  1. Introduction to join() method
  2. join() method example
  3. Different separator example

Let’s start today’s topic How to convert an array of strings to comma separated strings in Javascript?


Introduction to join() method

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

– MDN


join() method example

Here, we will see how we can use the javascript join() method to convert an array of strings to comma-separated strings.

let’s see what we can do.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// expected output: "Fire,Air,Water"

Here, we have to just use the join method on our array and it will return array elements separated by a comma.

JavaScript, array join example
JavaScript, array join example

Different separator example

Where, we will see how we can use the javascript join() method to convert an array of strings to space, hyphen ( - ) separated strings.

let’s see what we can do.

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join(' '));
// expected output: "Fire Air Water"

console.log(elements.join('-'));
// expected output: "Fire-Air-Water"

Here, we have to just use the join method on our array and pass separator as a parameter, it will return array elements separated by parameter.

JavaScript, array join parameter example
JavaScript, array join parameter example

All the best 👍.