Saturday, November 16, 2024
Google search engine
HomeLanguagesJavascriptHow to create a string by joining the elements of an array...

How to create a string by joining the elements of an array in JavaScript ?

Given an array containing array elements and here we will join all the array elements to make a single string. To join the array elements we use arr.join() method.

There are two methods by which we can create a string by joining the elements of an array:

Method 1: Using arr.join() Method

This method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(,).

Syntax:

array.join(separator)

Example: In this case, we use an empty separator i.e. array.join(“”) to join the array elements.

Javascript




let str = ["Welcome", "Geeks", "for", "Geeks"];
 
console.log("Joined String: " + str.join(""));


Output

Joined String: Welcomeneveropen

Method 2: Using arr.toString() Method

The JavaScript Array toString() Method returns the string representation of the array elements

Syntax:

arr.toString()

Example:

Javascript




// JavaScript to illustrate toString() method
function func() {
 
    // Original array
    let arr = ["Geeks", "for", "Geeks"];
 
    // Creating a string
    let str = arr.toString();
    console.log(str);
}
func();


Output

Geeks,for,Geeks

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments