JavaScript join() Method
This tutorial introduces the join() method, part of the JavaScript Array object. The join() method returns a string representation of an array, and accepts an optional string argument to join the array elements together.
Related array method:
The toString() method returns a string representation of an array, and separates array elements with a comma; toString() does not accept a separator argument.
Using the join() Method
We declare below a simple JavaScript array with three elements. We will use the join() method to display the array elements as a string.
var arlene = new Array("alpha", "beta", "gamma");
// Display one element per line with join() method
alert( arlene.join("\n") );
The script above produces the following result; the new line character ("\n") is inserted between each array element.
If no argument is supplied to the join() method, the array elements will be returned as a string, using a comma between each element.
Using the join() method without argument produces the same result as calling Array.toString()
, which inserts a comma between each element.
Test the join() Method
Interactively test the join() method by editing the JavaScript code below and clicking the Test join() Method button.
Browser support for JavaScript join() method | |||
---|---|---|---|