How to use the Array.join() method in JavaScript

The array.join() method will return a new string by concatenating all the elements of the array.

Error: Code Widget Crashed, Please Contact Support

The array method takes a separator as an argument. The separator will be placed between the elements of the array.

Error: Code Widget Crashed, Please Contact Support

If the array only contains one element, the separator will not be added.

Error: Code Widget Crashed, Please Contact Support

, is considered as the default separator.

Error: Code Widget Crashed, Please Contact Support

If the length of the array is 0, then the empty string is returned.

console.log("\n-------------\nIf the array length is 0 then empty string is returned");
let array = [];
let str = array.join('~~~~~~');
console.log("value after join empty array",str);

If an element of the array is undefined, null, or an empty array [], it is converted to an empty string.

console.log("If an array element is undefined or null then empty string is returned \n")
let array = [1,undefined,2,null,3,4];
let str = array.join(",");
console.log("After joining array", array, "\nThe returned value is ", str );

All elements are converted to a string before they are joined. If the array contains an object, it is converted to a string as well.

console.log("Joining object ");
let array = [{}, [1], "1"];
let str = array.join("-");
console.log("On joining", array, "\nThe returned sting is", str);

Complete code

let array = ["I", "Love", "Tamil", "language"];
console.log("\n-------------\nJoining array with separator ','");
let str = array.join(',');
console.log(str);
console.log("\n-------------\nJoining array without separator - by default ',' is considered as separator");
str = array.join();
console.log(str);
console.log("\n-------------\nJoining array with separator ' + ' ");
str = array.join(' + ');
console.log(str);
console.log("\nJoining array with empty string as separator ");
str = array.join('');
console.log(str);
console.log("\n-------------\nJoining array with space as separator ");
str = array.join(' ');
console.log(str);
console.log("\n-------------\nIf there is only one element in the array seperator will not be added");
array = ["Tamil"];
str = array.join(',');
console.log(str);
console.log("\n-------------\nIf the array length is 0 then empty string is returned");
array = [];
str = array.join('~~~~~~');
console.log(str);
console.log("\n-------------\nIf an array element is undefined or null then empty string is returned \n")
array = [1,undefined,2,null,3,4];
str = array.join(",");
console.log("After joining array", array, "\nThe returned value is ", str );
console.log("\n-------------\nJoining object ");
array = [{}, [1], "1"];
str = array.join("-");
console.log("On joining", array, "\nThe returned sting is", str);

Free Resources