The Array.join() method is a built-in JavaScript function used to join all elements of an array into a single string. The elements are separated by a specified delimiter or a comma (,
) if no delimiter is provided.
Syntax
arr.join(separator);
Parameters
Parameter | Description |
---|---|
separator | (Optional) A string is used to separate array elements in the resulting string. Defaults to a comma (, ) if not provided. |
Return Value
The join()
method returns a string containing all array elements joined by the specified separator. If the array is empty, it returns an empty string.
Example 1: Joining Array Elements with Default Separator
let arr = ['HTML', 'CSS', 'JavaScript']; let result = arr.join(); console.log(result); // Output: 'HTML,CSS,JavaScript'
The default separator (a comma) is used to join the array elements.
Example 2: Joining with a Custom Separator
let arr = ['HTML', 'CSS', 'JavaScript']; let result = arr.join(' - '); console.log(result); // Output: 'HTML - CSS - JavaScript'
Example 3: Joining an Array of Numbers
let arr = [10, 20, 30, 40, 50]; let result = arr.join(' | '); console.log(result); // Output: '10 | 20 | 30 | 40 | 50'
Example 4: Joining an Empty Array
let arr = []; let result = arr.join(); console.log(result); // Output: ''
Example 5: Handling undefined
and null
Values
let arr = [1, undefined, null, 4]; let result = arr.join(' - '); console.log(result); // Output: '1 - - - 4'
Example 6: Joining with No Separator
let arr = ['A', 'B', 'C']; let result = arr.join(''); console.log(result); // Output: 'ABC'
Example 7: Joining Nested Arrays
let arr = [1, [2, 3], 4]; let result = arr.join(); console.log(result); // Output: '1,2,3,4'
Supported Browsers
Browser | Support |
---|---|
Chrome | 1+ |
Firefox | 1+ |
Safari | 1+ |
Edge | 12+ |
Opera | 4+ |
Internet Explorer | 5.5+ |