JavaScript Join Array Method

By onjsdev

Javascriot provides a wide of range array methods to work on them. One of them is the join method, The join method takes an array and returns a string, where each element of the array is separated by a specified separator.


The syntax of the join method is as follows:


The separator parameter is optional and it specifies the character that separates the array elements in the resulting string. If the separator parameter is not specified, the elements are separated by commas.


Let's look at some examples to better understand how the join method works.

const array = ['apple', 'banana', 'cherry'];
const string1 = array.join();
console.log(string1); // Output: "apple,banana,cherry"

const string2 = array.join('-');
console.log(string2); // Output: "apple-banana-cherry"

In the first example, we use the join method without specifying a separator. As a result, the elements in the array are separated by commas in the resulting string. Unlike, In the second example that we use the join method with a hyphen separator. As a result, the elements in the array are separated by hyphens in the resulting string.

The join method can be useful when working with arrays consisting of strings, such as when creating HTML elements dynamically. For example, we could use the join method to create a list of HTML elements based on an array.

const fruits = ['apple', 'banana', 'cherry'];
const listItems = => `<li>${fruit}</li>`);
const list = `<ul>${listItems.join('')}</ul>`;
// Output: "<ul><li>apple</li><li>banana</li><li>cherry</li></ul>"

In this example, we use the map method to create an array of HTML list items based on the array of fruits. We then use the join method to combine the list items into a single string, which can be used to create an HTML list.


In conclusion, the join method is a useful tool for combining arrays into strings in JavaScript. It allows you to customize the separator between elements and can be used in a wide range of applications for formatting string data for display.

Thank you for reading.