'How to display all items from a javascript array in html with commas in between them except the last item

I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward? Below I have the code that prints all items in the array except the last one.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" type="text/css" href="coffee.css" />
    <title>Coffee</title>
  </head>
  <body>
   
    <section class="javascript">
      <h3>Drinks of the Month</h3>
      <p id="drinks"></p>
    </section>

    <script>
      var drinks = [
        "Chai Tea",
        "Sweet Cream Cold Brew",
        "Caramel Macchiato",
        "Vanilla Latte",
      ];

      var i = 0;
      var drinksOfMonth = "";
      while (i < drinks.length - 1) {
        drinksOfMonth += drinks[i] + ", ";
        i++;
      }


      document.getElementById("drinks").innerHTML = drinksOfMonth;
    </script>
  </body>
</html>


Solution 1:[1]

Just use join() method of array.

Example

const foo = ['tea', 'coffee', 'soda'];

console.log(foo.join('-'));
console.log(foo.join(', ');

You can read more about Array.join() here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

Solution 2:[2]

This will do it:

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
]

drinks.join(', ')

Will output:

Chai Tea, Sweet Cream Cold Brew, Caramel Macchiato, Vanilla Latte

Solution 3:[3]

You can also do it like this

while (i < drinks.length) { 
  if(i != drinks.length-1){
    drinksOfMonth += drinks[i] + ", "}
  else{
    drinksOfMonth += drinks[i]}
 i++ 
}

Solution 4:[4]

I have to use a for loop or while loop. How do I include the last item from the array without including the comma afterward ?

Why you want to use for or while loop as you can easily achieve this requirement with Array.join() method with a single line of code.

Demo :

var drinks = [
  "Chai Tea",
  "Sweet Cream Cold Brew",
  "Caramel Macchiato",
  "Vanilla Latte",
];

console.log(drinks.join(', '));

Solution 5:[5]

Just add the last item after the while loop:

drinksOfMonth += drinks[drinks.length-1];

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 true_k
Solution 2 Rob Kwasowski
Solution 3 Python learner
Solution 4 Rohìt Jíndal
Solution 5 FurrySenko