The join() method in JavaScript is used to join all elements of an array into a string. You can specify a separator that will be used to separate each element in the resulting string. If no separator is specified, a comma , will be used by default.
Syntax
array.join(separator);
Parameters
Parameters | Description |
---|---|
separator (Optional) | The string used to separate each element in the array. If omitted, a comma , will be used. |
Return Value
Return Type | Description |
---|---|
String | A string representing the joined elements. |
Example 1: Using join() to Convert an Array to a String
This code demonstrates how to use the join() method to convert an array into a string with elements separated by a comma.
let fruits = ['Apple', 'Banana', 'Orange']; let result = fruits.join(); console.log(result); // Output: "Apple,Banana,Orange"
Example 2: Using join() with a Custom Separator
You can specify a custom separator to be used in the resulting string.
let fruits = ['Apple', 'Banana', 'Orange']; let result = fruits.join(' and '); console.log(result); // Output: "Apple and Banana and Orange"
Example 4: Using join() with an Empty Separator
If you specify an empty string as the separator, the elements will be concatenated without any separator.
let fruits = ['Apple', 'Banana', 'Orange']; let result = fruits.join(''); console.log(result); // Output: "AppleBananaOrange"
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
1 | 12 | 1 | 4 | 1 |