JavaScript Array join()

Posted by

Method

JavaScript Array join() Method

The JavaScript Array join() method is used to join all elements of an array into a string. The elements of the array are separated by the separator specified in the parameter. If the argument is omitted, the array elements are separated by a comma.

The syntax of the join() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

array.join(separator);

[/dm_code_snippet]

Here, array is the name of the array, and separator is the character or string used to separate the elements of the array.

Example 1: Joining array elements without specifying a separator

In the following example, the elements of an array are joined without specifying a separator:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var colors = ["Red", "Green", "Blue"];

var strColors = colors.join();

console.log(strColors);  // Output: Red,Green,Blue

[/dm_code_snippet]

In this example, the join() method is used to join the elements of the colors array. Since no separator is specified, the elements are joined by a comma.

Example 2: Joining array elements with a separator

In the following example, the elements of an array are joined with a hyphen as a separator:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var numbers = [1, 2, 3, 4, 5];

var strNumbers = numbers.join("-");

console.log(strNumbers);  // Output: 1-2-3-4-5

[/dm_code_snippet]

In this example, the join() method is used to join the elements of the numbers array. The hyphen is specified as the separator.

Example 3: Joining array elements with a custom separator

In the following example, the elements of an array are joined with a custom separator:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

var fruits = ["Apple", "Banana", "Orange"];

var strFruits = fruits.join(" --> ");

console.log(strFruits);  // Output: Apple --> Banana --> Orange

[/dm_code_snippet]

In this example, the join() method is used to join the elements of the fruits array. The custom separator “–>” is specified as the separator.

Conclusion

The JavaScript Array join() method is used to join all elements of an array into a string. The separator specified in the parameter is used to separate the elements of the array. If the argument is omitted, the array elements are separated by a comma.