Loop to print iterations separated with a comma, with no comma at the end

javascript

Solution

You should use `join()` instead. It's much cleaner and you don't need to worry about edge cases:

  var printSeven = document.getElementById('multiples_seven');
  var sevens = [];
  for (i=1; i <= 1000; i++){
      if (i % 7 == 0){
        sevens.push(i);
      }
  }
  printSeven.innerText = sevens.join(", ");

Or an approach that avoids the `if()` statement and unnecessary iterations:

  var printSeven = document.getElementById('multiples_seven');
  var sevens = [];
  for (i = 7; i <= 1000; i += 7){
     sevens.push(i);
  }
  printSeven.innerText = sevens.join(", ");

And for the sake of understanding, here's how you could do this without `join()`:

  var printSeven = document.getElementById('multiples_seven');
  var maxValue = 1000;
  var list = "";

  for (i = 7; i <= maxValue; i += 7){
     list += i;
     if(i + 7 <= maxValue){
       list += ", ";
     }
  }
  printSeven.innerText = list;

Problem

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please ``` window.onload = function(){ var mySeven = 0; var printSeven = document.getElementById('multiples_seven'); for (i=1; i <= 1000; i++){ if (i % 7 == 0){ mySeven += i; printSeven.innerHTML += i + ',' + ' '; } } }; ``` Thanks!

Original source