JavaScript Array .join() Method

The join method combines all the elements contained in an array and returns it as a string separated by a comma (,) or any specified string separator.

The method will return an empty string if the length of the array is 0.

// create an array
const words = ['Hello', 'there', 'world!'];

// join the array with spaces in between
const greeting = words.join(' WOW ');

console.log(greeting); // Hello WOW there WOW world!

The join method:

  • Takes an optional separator.
  • Concatenates the elements of the array separated by the provided separator or the default separator which is a comma.

1 Parameter

This method takes one parameter:

  • separator : a string provided to be used as a separator while concatenating the elements - optional.

Returns a New String

The method will return a string containing all the elements contained in the array or an empty string if the array is empty.

// create a string
const names = ['John', 'Peter', 'James', 'Pammy'];

const myName = names.join();
// output: 'James, Peter, James, Pammy'

Basic Usage

Concatenating the elements in an array using a separator.

Remove all commas within a string

Some of the popular use cases of join is in combination with the split string method.
E.g - Removing all the commas within a string.