This post will discuss how to join elements of an array with a delimiter in JavaScript.

1. Using Array.join() function

One way to join elements of an array using delimiter in JavaScript is to use the Array.join() function. This function joins the elements of an array into a string, separated by a specified delimiter. For example, if we have an array of numbers and we want to convert it to a string using a dash (-) as a separator, we can do this:

Download  Run Code

 
We can use any character or string as the delimiter, such as a comma (,), a space ( ), or a plus sign (+). If we don’t provide any argument to the join() function, it will use the default delimiter, which is a comma (,). Here’s an example:

Download  Run Code

2. Using Array.reduce() function

Another way to convert an array to a string using a delimiter is to use the Array.reduce() function. This is a third built-in function that executes a reducer function on each element of the array, resulting in a single output value. We can use this function to convert an array to a string by concatenating each element with a delimiter of our choice. For example, if we have an array of strings and we want to convert it to a string using a slash (/) as the delimiter, we can do this:

Download  Run Code

 
We can also provide an initial value for the accumulator as the second argument to the reduce() function. Here’s an example:

Download  Run Code

3. Using Array.toString() function

This is another built-in function that returns a string representing the specified array and its elements. This function is equivalent to calling the join() function without any arguments, which means it uses a comma as the default separator. For example:

Download  Run Code

4. Using Array.map() function

We can also use other functions, such as Array.map(), to join the array elements with a delimiter and perform some additional operations on them. For example, if we want to join the array elements with a space ( ) and capitalize the first letter of each element, we can use the Array.map() function like this:

Download  Run Code

That’s all about joining elements of an array with a delimiter in JavaScript.