Javascript Array join()

The join() method returns a new string by concatenating all of the elements in an array, separated by a specified separator.

Example

let message = ["JavaScript", "is", "fun."];

// join all elements of array using space
let joinedMessage = message.join(" ");
console.log(joinedMessage);

// Output: JavaScript is fun.

join() Syntax

The syntax of the join() method is:

arr.join(separator)

Here, arr is an array.


join() Parameters

The join() method takes in:

  • separator (optional) - A string to separate each pair of adjacent elements of the array. By default, it is comma ,.

join() Return Value

  • Returns a String with all the array elements joined by separator.

Notes:

  • The join() method does not change the original array.
  • Elements like undefined, null, or empty array have an empty string representation.

Example: Using join() method

var info = ["Terence", 28, "Kathmandu"];

var info_str = info.join(" | ");
// join() does not change the original array console.log(info); // [ 'Terence', 28, 'Kathmandu' ] // join() returns the string by joining with separator console.log(info_str); // Terence | 28 | Kathmandu // empty argument = no separator var collection = [3, ".", 1, 4, 1, 5, 9, 2];
console.log(collection.join("")); // 3.141592
var random = [44, "abc", undefined];
console.log(random.join(" and ")); // 44 and abc and

Output

[ 'Terence', 28, 'Kathmandu' ]
Terence | 28 | Kathmandu
3.141592
44 and abc and 

Here, we can see that the join() method converts all the array elements into a string and separates each element by the specified separator.


Also Read:

Did you find this article helpful?

Your builder path starts here. Builders don't just know how to code, they create solutions that matter.

Escape tutorial hell and ship real projects.

Try Programiz PRO
  • Real-World Projects
  • On-Demand Learning
  • AI Mentor
  • Builder Community