In JavaScript, array elements can be combined into a single string using built-in methods or a loop.
- join() combines array elements using a specified separator.
- toString() converts the array into a comma-separated string.
- A for loop can be used when custom joining logic is required.
Approach 1: Using join() Method
The join() method combines all elements of an array into a string. It accepts an optional separator, which is a comma (,) by default.
Syntax:
array.join(separator)Example: Use an empty separator to join all array elements without any space or character between them.
let str = ["Welcome", "Geeks", "for", "Geeks"];
console.log("Joined String: " + str.join(""));
Output
Joined String: WelcomeGeeksforGeeks
Approach 2: Using toString() Method
The toString() method converts an array into a string representation. Array elements are separated by commas.
Syntax:
array.toString()Example: Use toString() to convert the array elements into a single string.
let arr = ["Geeks", "for", "Geeks"];
let str = arr.toString();
console.log(str);
Output
Geeks,for,Geeks
Approach 3: Using for Loop
A for loop can be used to iterate through each array element and concatenate them into a string. This approach provides more control over the joining logic.
Example: Iterate through the array and add a space between consecutive elements.
let array = ["Welcome", "to", "GeeksforGeeks"];
let string = "";
for (let i = 0; i < array.length; i++) {
string += array[i];
if (i < array.length - 1) {
string += " ";
}
}
console.log(string);
Output
Welcome to GeeksforGeeks