JavaScript Array join() method
JavaScript Array join() method is used to join the elements of this Array into a string, using the given delimiter value.
Syntax
The syntax to call join() method on an array x
is
</>
Copy
x.join()
x.join(',')
If no delimiter value is passed as argument to join() method, then the default value ','
would take affect.
Examples
In the following example, we take an array of fruit names, and join them with default delimiter using join() method.
index.html
<!doctype html>
<html>
<body>
<pre id="output"></pre>
<script>
var fruits = ['apple', 'banana', 'cherry'];
var result = fruits.join();
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Now, let us specify a delimiter to the join() method.
index.html
<!doctype html>
<html>
<body>
<pre id="output"></pre>
<script>
var fruits = ['apple', 'banana', 'cherry'];
var result = fruits.join('-----');
document.getElementById("output").innerHTML = result;
</script>
</body>
</html>
Conclusion
In this JavaScript Tutorial, we have learnt how to use join() method on an Array to join the elements of the Array and return a string.