The join()
method is used to join the elements of an array into a string and return the string.
The method consists of an optional separator
parameter which is used to specify how you want to join the elements.
let numbers = [5, 6, 7, 8, 9];
let str = numbers.join(' ');
console.log(str); // 5 6 7 8 9
Another example, with strings as elements.
let numbers = ["I", "love", "Javascript."];
let str = numbers.join(' ');
console.log(str); // I love Javascript.
The separator can be any string. For example,
let numbers = ["I", "love", "Javascript."];
let str = numbers.join('-');
console.log(str); // I-love-Javascript.
str = numbers.join('00');
console.log(str); // I00love00Javascript.
This method can be useful when you are using a split()
method to split a string into an array. The join() method can help convert the array to a string.
let string = "lorem ipsum dolor sit amet.";
let arr = string.split(' ').reverse();
console.log(arr); // ['amet.', 'sit', 'dolor', 'ipsum', 'lorem']
console.log(arr.join(' ')); // amet. sit dolor ipsum lorem
If you do not pass any argument to the join()
method, it will use ,
by default.
let arr = ['lorem', 'ipsum', 'dolor', 'sit', 'amet.'];
let newStr = arr.join();
console.log(newStr); // lorem,ipsum,dolor,sit,amet.