Tutorialspoint.dev

JavaScript | Array join() function

Array.join() function is used to join the elements of the array together into a string.

Syntax:

Array.join([separator])

Argument: (separator)
A string to separate each elements of the array. If leave it by default array element separate by comma( , ).

Return Value:
This function returns a string created by joining all the elements of the array using the separator. If the separator is not provided then the array elements are joined using comma ( , ) as it is the default separator for this function. If an empty string is provided as the separator then the elements are joined directly without any character in between them. If array is empty then this function returns an empty string.

Examples for the above function are provided below:



Example 1:

var a = [1, 2, 3, 4, 5, 6];
print(a.join('|'));

Output:

1|2|3|4|5|6

In this example the function join() joins together the elements of the array into a string using ‘|’.

Example 2:

var a = [1, 2, 3, 4, 5, 6];
print(a.join()); 

Output:

1, 2, 3, 4, 5, 6

In this example the function join() joins together the elements of the array into a string using ‘, ‘ since it is the default value.

Example 3:

var a = [1, 2, 3, 4, 5, 6];
print(a.join(''));

Output:

123456

In this example the function join() joins together the elements of the array into a string using ‘ ‘ (empty string).

Codes for the above function are provided below:



Program 1:

// JavaScript code for join() function
<script>
function func() {
  var a = [ 1, 2, 3, 4, 5, 6 ];
  document.write(a.join('|'));
}
  
func();
< /script>

Output:

1|2|3|4|5|6

Program 2:

// JavaScript code for join() function
<script>
function func() {
  var a = [ 1, 2, 3, 4, 5, 6 ];
  document.write(a.join());
  
func();
< /script>

Output:

1, 2, 3, 4, 5, 6

Program 3:

// JavaScript code for join() function
<script>
function func() {
  var a = [ 1, 2, 3, 4, 5, 6 ];
  document.write(a.join(''));
}
  
func();
< /script>

Output:

123456


This article is attributed to GeeksforGeeks.org

You Might Also Like

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter