Introduction to JavaScript join() Method
In JavaScript, the join
method is a built-in method of the Array prototype that is used to create a string from the elements of an array. This method is often used to convert an array of data into a human-readable string, such as a list of names or a sequence of numbers.
In this article, we will discuss how to use the join
method in JavaScript.
Using the JavaScript join()
method
The join
method accepts a single argument: a string that specifies the separator to use between the elements of the array. This separator is inserted between each element of the array when the string is created, and it determines how the elements of the array are combined to form the final string. Here is an example of how to use the "join" method to create a string from the elements of an array:
let myArray = [1, 2, 3, 4, 5];
let myString = myArray.join(", ");
console.log(myString);
Output
1, 2, 3, 4, 5
In this example, the join
method is called on the myArray
array, and it is passed a string containing a comma and a whitespace as its argument. This specifies that the elements of the array should be separated by a comma and a space when the string is created. The result is then assigned to the myString
variable, and it is logged to the console.
In addition to specifying a separator string, you can also use the join
method without any arguments, in which case the elements of the array will be separated by a default separator of ","
. Here is an example of how to use the join
method without any arguments:
let myArray = [1, 2, 3, 4, 5];
let myString = myArray.join();
console.log(myString);
Output
1,2,3,4,5
In this example, the join
method is called on the myArray
array without any arguments, which specifies that the elements of the array should be separated by a default separator of ","
. The result is then assigned to the myString
variable, and it is logged to the console.
Summary
The join
method is a built-in method of the Array prototype in JavaScript that is used to create a string from the elements of an array. This method accepts a single argument: a string that specifies the separator to use between the elements of the array. If no separator is specified, the elements of the array are separated by a default separator of ",". The join
method is useful for converting an array of data into a human-readable
References
Array.prototype.join() - JavaScript | MDN (mozilla.org)