• JavaScript Video Tutorials

JavaScript - Array join() Method



The JavaScript Array join() method is used to concatenate the array elements with a specified separator and returns the result as a string.

  • If no separator is specified, the array elements will be separated by (,) comma by default.
  • This method does not change the original array instead, it returns a new string as a result.
  • If the array has only one item, then the value will be returned without a separator.

Syntax

Following is the syntax of JavaScript Array join() method −

array.join(separator);

Parameters

This method accepts only one parameter. The same is described below −

  • The "separator" is a string that separates the elements in the resulting string. By default, it separated with (,) comma.

Return value

A string representing the elements of the array joined by the specified separator.

Examples

Example 1

If we do not pass any separator to the JavaScript Array copyWithin() method, it will separate the elements with (,) comma by default.

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
      let result = animals.join();
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

As we can see the output, all the elements in the array are seperated with (,) comma.

Lion,Chetaah,Tiger,Elephant,Dinosaur

Example 2

Here, we are passing an empty string as a parameter to this function. So that, it will return the elements without a (,) comma and no space in between them −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
      let result = animals.join("");
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

After executing the above program, the array elements will be separated with no space in between them.

LionChetaahTigerElephantDinosaur

Example 3

Here, we are passing "and" as a separator to this function. So that, the array elements will be separated by "and" −

<html>
<body>
   <p id="demo"></p>
   <script>
      const animals = ["Lion", "Chetaah", "Tiger", "Elephant", "Dinosaur"];
      let result = animals.join(" and ");
      document.getElementById("demo").innerHTML = result;
   </script>
</body>
</html>

Output

After executing the above program, the array elements will be separated by "and".

Lion and Chetaah and Tiger and Elephant and Dinosaur
Advertisements