JavaScript join() | Convert an Array into a String

The JavaScript join() method returns a string from specified array. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p>The value of 'myString': <span id="xyz"></span></p>

   <script>
      const myArray = ["codes", "cracker", ".", "com"];
      let myString = myArray.join("");
      document.getElementById("xyz").innerHTML = myString;
   </script>
   
</body>
</html>
Output

The value of 'myString':

JavaScript join() Syntax

The syntax of join() method in JavaScript, is:

array.join(separator)

The separator parameter is used to separate each items of the array when creating the string. The default value is comma (,). For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="abc"></p>

   <script>
      const cities = ["Tokyo", "Los Angeles", "Bangkok", "Dubai"];
      let str = cities.join();
      document.getElementById("abc").innerHTML = str;
   </script>
   
</body>
</html>
Output

You can use any desired separator to separate each and every items of the array, while joining them and creating a string. For example:

HTML with JavaScript Code
<!DOCTYPE html>
<html>
<body>

   <p id="mypara"></p>

   <script>
      const c = ["Tokyo", "Los Angeles", "Bangkok", "Dubai"];
      let s = c.join(" | ");
      document.getElementById("mypara").innerHTML = s;
   </script>
   
</body>
</html>
Output

JavaScript Online Test


« Previous Tutorial Next Tutorial »