Join Elements of Array in JavaScript
In JavaScript, Array.join()
method is used to join elements of the array by a given separator.
Syntax
array.join(separator)
array
is an array of elements.join
is the array method name.separator
is an optional string value. default value is comma.
join()
method joins the elements of the array with the given separator
string, and returns the result as a string. join()
method does not modify the original array.
Examples
1. Join the elements of the array fruits
with '-'
hyphen character as separator.
let fruits = ['apple', 'banana', 'cherry'];
let separator = '-';
output = fruits.join(separator);
console.log(output);
2. Call join()
method on fruits
array with no separator passed.
let fruits = ['apple', 'banana', 'cherry'];
let output = fruits.join();
console.log(output);
Since comma is the default separator, we get a comma separated elements in the resulting string.