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:
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
andundefined
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
Example 2: Using a custom separator
Example 3: Joining with no separator
Example 4: Handling null
and undefined
values
Example 5: Joining numbers
Example 6: Joining an empty array
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
andundefined
. - This method does not alter the original array, making it safe for use when you need to retain the original data structure.