The JavaScript join() method is used to combine all elements of an array into a single string. The elements are separated by a specified separator, with a comma (,) as the default.
- Does not modify the original array; it returns a new string.
- You can specify any separator such as " ", "-", or "|".
- If no separator is provided, elements are joined using a comma (,).
Syntax
array.join(separator);Parameters
This method accepts a single parameter as mentioned above and described below:
- separator: It is Optional i.e., it can be either used as a parameter or not. Its default value is a comma(, ).
[Example 1]: In this example, the function join() joins together the elements of the array into a string using ‘|’.
function func() {
let a = [1, 2, 3, 4, 5, 6];
console.log(a.join('|'));
}
func();
[Example 2]: In this example, the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value.
let a = [1, 2, 3, 4, 5, 6];
console.log(a.join());
[Example 3]: In this example, the function join() joins together the elements of the array into a string using ‘ ‘ (empty string).
let a = [1, 2, 3, 4, 5, 6];
console.log(a.join(''));