JavaScript Array join()
Syntax & Examples
Array.join() method
The join() method of the Array class in JavaScript joins all elements of an array into a string. If no separator is provided, a comma (,) is used by default.
Syntax of Array.join()
There are 2 variations for the syntax of Array.join() method. They are:
join()
This method joins all elements of an array into a string, using a comma (,) as the default separator.
Returns value of type String
.
join(separator)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
separator | optional | A string to separate each pair of adjacent elements in the array. Defaults to a comma (,). |
This method joins all elements of an array into a string, using the specified separator.
Returns value of type String
.
✐ Examples
1 Using join() method with default separator
In JavaScript, we can use the join() method to join all elements of an array into a string with a comma (,) as the default separator.
For example,
- We define an array variable arr with elements [1, 2, 3, 4, 5].
- We use the join() method on arr without specifying a separator.
- The result is stored in the variable joinedString.
- We log joinedString to the console using console.log() method to see the joined string.
JavaScript Program
const arr = [1, 2, 3, 4, 5];
const joinedString = arr.join();
console.log(joinedString);
Output
1,2,3,4,5
2 Using join() method with a specified separator
We can use the join() method to join all elements of an array into a string with a specified separator.
For example,
- We define an array variable arr with elements ['apple', 'banana', 'cherry'].
- We use the join() method on arr with a hyphen (-) as the separator.
- The result is stored in the variable joinedString.
- We log joinedString to the console using console.log() method to see the joined string.
JavaScript Program
const arr = ['apple', 'banana', 'cherry'];
const joinedString = arr.join('-');
console.log(joinedString);
Output
apple-banana-cherry
3 Using join() method to join elements of an array of numbers with a space separator
We can use the join() method to join all elements of an array of numbers into a string with a space separator.
For example,
- We define an array variable numArr with elements [10, 20, 30, 40, 50].
- We use the join() method on numArr with a space as the separator.
- The result is stored in the variable joinedString.
- We log joinedString to the console using console.log() method to see the joined string.
JavaScript Program
const numArr = [10, 20, 30, 40, 50];
const joinedString = numArr.join(' ');
console.log(joinedString);
Output
10 20 30 40 50
Summary
In this JavaScript tutorial, we learned about join() method of Array: the syntax and few working examples with output and detailed explanation for each example.