AppDividend
Latest Code Tutorials

Javascript Array Join: How to Join Array in JavaScript

Javascript array join() is an inbuilt method that creates and returns the new string by concatenating all of the elements of the array. The join() method joins the items of the array into the string and returns that string. The specified separator will separate the array items. The default separator is a comma (,).

Javascript Array join()

Javascript join() method returns the array as a string. The elements will be separated by a specified separator. The default separator is a comma (,).

Syntax

The syntax for the join() method is the following.

array.join(separator)

Parameters

The separator is an optional parameter. By default, a separator is a comma.

A simple example is the following.

// app.js

let apps = ["Instagram", "Facebook", "Messanger"];
let fb = apps.join();

console.log(fb);

Output

Javascript Array Join Example | Array.prototype.join() Tutorial

So, it returns a comma-separated string. We did not pass any parameter to the join() function that is why it has returned the comma-separated string.

// app.js

let apps = ["Instagram", "Facebook", "Messanger"];
let fb = apps.join('_');

console.log(fb);

It will return the underscore separated string.

So, an Array.join() function is used to join all the items of an array together into a string.

If an element is undefined or null, it is converted to the empty string. So If an array.length is 0, the empty string is returned.

Joining an array of four different ways

The following example is an array, with three elements, then joins the array four times: using the default separator, then a comma and space, then a plus and an empty string.

let suits = ['Harvey', 'Mike', 'Louis'];
suits.join();      // 'Harvey,Harvey,Louis'
suits.join(', ');  // 'Harvey, Harvey, Louis'
suits.join(' + '); // 'Harvey + Harvey + Louis'
suits.join('');    // 'HarveyHarveyLouis'

Joining an array-like object

The following example joins an array-like object (arguments), by calling Function.prototype.call on Array.prototype.join.

// app.js

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

Output

Javascript Array Join Example

Finally, Javascript array join() example tutorial is over.

2 Comments
  1. Syed Noman Ahmed says

    Hey. Thanks for putting this together. It is really useful to understand how Array.join() works. I would highlight one quick thing that you might want to fix is the output in the examples under section “Joining an array of four different ways”. You have mentioned Harvey Harvey Louis in the four outputs. I believe you need to have Harvey Mike Louis in the output. Thanks

  2. Amit Parmar says

    thanks for the guide

Leave A Reply

Your email address will not be published.

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