JavaScript join(): Convert an array into a string

The JavaScript join() method returns a string from a 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 the join() method in JavaScript is:

array.join(separator)

The separator parameter is used to separate each item of the array when creating the string. The default value is a 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 item 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 »


Liked this article? Share it!





Like/follow us on social media for updates!




Like/follow us on social media for updates!