JavaScript Array join() Method

JavaScript Array join() method joins the elements of an array into a string using the specified separator. It does not change the original array.

Syntax

array.join(separator)

Parameters

separator(optional): It specifies what to put between the array elements. By default, a separator is a comma.

Return value

Returns array values, separated by the specified separator.

Visual RepresentationVisual Representation of JavaScript Array join() Method

Example 1: How to Use Array join() method

let apps = ["Insta", "Fb", "Snap", "x", "Youtube"];
let apps_join = apps.join();

console.log(app_join);

Output

Insta,Fb,Snap,x,Youtube

In the above example, the array apps convert to a string where each element of the array is separated by a default specifier(comma).

Example 2: Joining an array using a custom separatorVisual Representation of Joining an array using a custom separator

let apps = ["Insta", "Fb", "Snap", "x", "Youtube"]; 

let apps_join = apps.join('|'); 
console.log(apps_join);

letplus_join = apps.join(' + ');
console.log(letplus_join);

Output

Insta|Fb|Snap|x|Youtube
Insta + Fb + Snap + x + Youtube

Example 3: Using empty stringVisual Representation of Using empty string

let apps = ["Insta", "Fb", "Snap", "x", "Youtube"];
let apps_join = apps.join(''); 
console.log(apps_join);

Output

InstaFbSnapxYoutube

Example 4: Using sparse arrays

This function treats empty slots like undefined ones and produces an extra separator.

let apps = ["Insta", , "Snap", , "Youtube"]; 
let apps_join = apps.join(); 
console.log(apps_join);

Output

Insta,,Snap,,Youtube

Example 5: Passing non-array objects

function aros(a, b, c) {
  let data = Array.prototype.join.call(arguments);
  console.log(data);
}

aros(21, 'acme', false);

Output

21,acme,false

Browser compatibility

  1. Google Chrome 1 and above
  2. Microsoft Edge 12 and above
  3. Mozilla Firefox 1 and above
  4. Safari 1 and above
  5. Opera 4 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.