join() method has the following syntax:
array: The array you want to join.
separator(optional): A string that specifies how the array elements should be separated in the resulting string. If omitted, the array elements will be separated by a comma.
const fruits = ["apple", "banana", "cherry"]; const joinedFruits = fruits.join(); console.log(joinedFruits); //"apple,banana,cherry"
In this example, the
join() method joins the elements of the
fruits array using the default separator, which is a comma.
Example 2: Custom Separator in join method
You can specify a custom separator as an argument to the
const colors = ["red", "green", "blue"]; const joinedColors = colors.join(" | "); console.log(joinedColors); // "red | green | blue"
" | " as the separator, we get a string where the array elements are separated by a vertical bar and space.
join() method can also be used with an empty array:
const emptyArray = ; const result = emptyArray.join("-"); console.log(result); // ""
In this case, the result is an empty string, as there are no elements in the array.
You can join arrays of numbers as well:
const numbers = [1, 2, 3, 4, 5]; const joinedNumbers = numbers.join(" + "); console.log(joinedNumbers); // "1 + 2 + 3 + 4 + 5"
Here, we’re using the
join() method to concatenate the numbers with a ” + ” separator.
You can join arrays containing mixed data types, such as strings and numbers:
const mixedData = ["apple", 3, "banana", 5, "cherry"]; const joinedMixedData = mixedData.join(" | "); console.log(joinedMixedData); // "apple | 3 | banana | 5 | cherry"
join() method works seamlessly with mixed data types, converting them all to strings.
join() method is a simple yet powerful tool for concatenating array elements into a string. It’s easy to use and versatile, allowing you to specify custom separators or use the default comma. It’s especially helpful when you need to format data for display or when working with dynamic content.