JavaScript Array join() method


The join() method in JavaScript is used to create a string by concatenating all the elements of an array, with a specified separator between each element. If no separator is provided, the default separator is a comma (,).

Syntax:

let result = array.join(separator);
  • separator (optional): A string used to separate the elements in the resulting string. If omitted, a comma (,) is used as the default separator.

Return Value:

  • A string that consists of the array elements joined together, separated by the specified separator.

Key Points:

  • If the array is empty, the method returns an empty string.
  • null and undefined elements in the array are converted to strings and included in the resulting string.
  • The method does not modify the original array; it returns a new string.

Example 1: Basic usage with default separator

let fruits = ['apple', 'banana', 'cherry']; let result = fruits.join(); // Use default separator (comma) console.log(result); // "apple,banana,cherry"

Example 2: Using a custom separator

let fruits = ['apple', 'banana', 'cherry']; let result = fruits.join(' - '); // Use a dash as the separator console.log(result); // "apple - banana - cherry"

Example 3: Joining with no separator

let fruits = ['apple', 'banana', 'cherry']; let result = fruits.join(''); // No separator console.log(result); // "applebananacherry"

Example 4: Handling null and undefined values

let mixedArray = ['apple', null, 'banana', undefined, 'cherry']; let result = mixedArray.join(' | '); // Use pipe as the separator console.log(result); // "apple | | banana | cherry"

Example 5: Joining numbers

let numbers = [1, 2, 3, 4, 5]; let result = numbers.join('-'); // Join numbers with a hyphen console.log(result); // "1-2-3-4-5"

Example 6: Joining an empty array

let emptyArray = []; let result = emptyArray.join(); // Joining an empty array console.log(result); // ""

Summary:

  • The join() method is a straightforward way to convert an array into a string, using a specified separator to format the output.
  • It's versatile and can handle various data types, including strings, numbers, and special values like null and undefined.
  • This method does not alter the original array, making it safe for use when you need to retain the original data structure.