Array.join()

The Array.join() method in JavaScript is used to create a string by concatenating all elements of an array, separated by a specified delimiter. If no delimiter is provided, the elements are joined using a comma (,) by default.

Syntax

</>
Copy
join()
join(separator)

Parameters

ParameterDescription
separator(Optional) A string used to separate each element in the array. If not provided, a comma (,) is used by default. If the separator is an empty string (""), the elements are joined without any delimiter.

Return Value

The join() method returns a string that is the concatenation of all elements of the array, separated by the specified delimiter.


Examples

1. Using Default Separator

If no separator is provided, the elements of the array are joined with a comma (,).

</>
Copy
const fruits = ["apple", "banana", "cherry"];

const result = fruits.join();
console.log(result);

Output

apple,banana,cherry
  1. The elements of fruits are joined using the default separator (,).

2. Using a Custom Separator

In this example, a hyphen (-) is used as the separator.

</>
Copy
const fruits = ["apple", "banana", "cherry"];

const result = fruits.join("-");
console.log(result);

Output

apple-banana-cherry
  1. fruits.join("-") joins the elements with a hyphen (-) as the separator.

3. Joining with an Empty String

Using an empty string ("") as the separator results in the elements being joined without any delimiter.

</>
Copy
const numbers = [1, 2, 3, 4];

const result = numbers.join("");
console.log(result);

Output

1234

4. Joining an Empty Array

If the array is empty, the join() method returns an empty string.

</>
Copy
const emptyArray = [];

const result = emptyArray.join();
console.log(result);

Output

An empty array always produces an empty string as the output.

5. Joining Arrays Containing undefined or null

When the array contains undefined or null, they are converted to empty strings in the result.

</>
Copy
const mixedArray = [1, null, 2, undefined, 3];

const result = mixedArray.join("-");
console.log(result);

Output

1--2--3

null and undefined are treated as empty strings in the joined result.