JavScript Array join() method

The join() method in JavaScript is used to join all elements of an array into a string. This method returns a string with all the array elements joined by a specified separator. For example:

const array1 = ['apple', 'banana', 'orange'];
const separator = ', ';
const result = array1.join(separator);

// the result will be: "apple, banana, orange"

In the code example above, we first declare an array called array1 that contains three strings: apple, banana, and orange. We then declare a variable called separator that contains the string we want to use to separate the elements of the array in the resulting string. In this case, we use a comma followed by a space. Finally, we use the join() method on the array1 array, passing in the separator variable as an argument. This returns a string with the elements of array1 joined together with the specified separator.

Note that if you don’t specify a separator, the join() method will use a comma (,) as the default separator. For example:

const array1 = ['apple', 'banana', 'orange'];
const result = array1.join();

// the result will be: "apple,banana,orange"

In the code example above, we use the join() method without specifying a separator. This means that the default separator (a comma) will be used, and the resulting string will have the elements of array1 separated by commas.

Leave a comment

Blog at WordPress.com.