The join() method of the Array class in JavaScript joins all elements of an array into a string. If no separator is provided, a comma (,) is used by default.
There are 2 variations for the syntax of Array.join() method. They are:
join()
This method joins all elements of an array into a string, using a comma (,) as the default separator.
Returns value of type String
.
join(separator)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
separator | optional | A string to separate each pair of adjacent elements in the array. Defaults to a comma (,). |
This method joins all elements of an array into a string, using the specified separator.
Returns value of type String
.
In JavaScript, we can use the join() method to join all elements of an array into a string with a comma (,) as the default separator.
For example,
const arr = [1, 2, 3, 4, 5];
const joinedString = arr.join();
console.log(joinedString);
1,2,3,4,5
We can use the join() method to join all elements of an array into a string with a specified separator.
For example,
const arr = ['apple', 'banana', 'cherry'];
const joinedString = arr.join('-');
console.log(joinedString);
apple-banana-cherry
We can use the join() method to join all elements of an array of numbers into a string with a space separator.
For example,
const numArr = [10, 20, 30, 40, 50];
const joinedString = numArr.join(' ');
console.log(joinedString);
10 20 30 40 50
In this JavaScript tutorial, we learned about join() method of Array: the syntax and few working examples with output and detailed explanation for each example.