Array.prototype.join()
The join()
method creates and returns a new string by concatenating all of the elements in the array, separated by a specified separator string. The default separator value is comma (,).
Syntax
arr.join([separator])
separator
parameter is optional. If ommited, the elements are separated by comma (,).
If an element is undefined, null or an empty array [], it is converted to an empty string.
console.log([].join()); // expected output: ''
console.log([null].join()); // expected output: ''
console.log([undefined].join()); // expected output: ''
Basic Examples
let fruits = ['apple', 'banana', 'kiwi', 'grape'];
console.log(fruits.join()); // expected output: 'apple,banana,kiwi,grape'
console.log(fruits.join('')); // expected output: 'applebananakiwigrape'
console.log(fruits.join(' ')); // expected output: 'apple banana kiwi grape'
console.log(fruits.join('_')); // expected output: 'apple_banana_kiwi_grape'
join
method
Common uses of let fruits = ['apple', 'banana', 'kiwi', 'grape'];
let sentence = `My favorite fruits are ${fruits.slice(0, -1).join(', ')} and ${fruits.slice(-1)}.`;
console.log(sentence); // expected output: 'My favorite fruits are apple, banana, kiwi and grape.'
.join()
is in combination with the .split()
string method:
Some of the popular use cases of const isPalindrom = str => {
str = str.toLowerCase();
return str === str.split('').reverse().join('');
}
isPalindrom('Level'); // expected output: true
let = str= 'I, would, like, to, be, an, expert, in, Javascript.';
console.log(str.split(', ').join(' ')); // expected output: 'I would like to be an expert in Javascript.'
const url = 'https://get.js.help';
const urlSlug = title => {
let pageUrl = title.toLowerCase().split(' ');
return `${url}/${pageUrl.join('-')}`
}
let postTitle = 'Complete React Firebase App Workshop';
console.log(urlSlug(postTitle)); // expected output: https://get.js.help/complete-react-firebase-app-workshop
List of methods and techniques which were used in the examples above and you may be curious to learn more about them:
- slice - copies a given part of an array and returns that copied part as a new array.
- split - divides a string into substrings and returns them as an array.
- reverse - reverses order of all elements in an array.
- toLowerCase - converts a string to lowercase letters.
List of Resources
MDN: Array.prototype.join()
Scotch.io: Array .join() Method
freeCodeCamp: How to Manipulate Arrays in JavaScript