JavaScript join: The Complete Guide

2
31
Javascript array join method tutorial with example

JavaScript join() method returns the array as a string. A specified separator will separate the elements. The default separator is a comma (,).

JavaScript join

JavaScript array join() is a built-in method that creates and returns the new string by concatenating all of the elements of the array. The join() method joins the array’s items into the string and returns that string. The specified separator will separate the array of elements. 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, which 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 combine all the items of an array into a string.

If an element is undefined or null, it is converted to an 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

That’s it for this tutorial.

2 Comments

  1. 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

Leave A Reply

Please enter your comment!
Please enter your name here

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