Search code examples
javascriptif-statementfor-loopfizzbuzz

Fizzbuzz game with for loop


I'm trying to do a function that'll print the numbers between 1-27 in my console.log.

When a number can be divided by 3, it should replace the number with "Fizz"
When a number can be divided by 5, replace it with "Buzz".
If the number can be divided by both 3 and 5, replace it with "Fizzbuzz"

Reference: http://en.wikipedia.org/wiki/Fizz_buzz)

This is my code:

 var fizzbuzz = function(start,stop) {
    for (var x=1;x <= stop; x++)
        var string =',';
    if (x%3 == 0) {
            string += 'Fizz';
    }
    if (x%5 ==  0){
        string += 'Buzz';
    }
    if (x%5 && x%3){
        string += 'Fizzbuzz';
    }
    return string;
};

Console.log is giving me "," and I'm not sure what I've done wrong.

Just to clarify. I want my answer to print out 1,2,Fizz,4,Buzz,Fizz,7,8,Fizz,Buzz,11,Fizz,13,14,Fizz Buzz,16,17,Fizz,19,Buzz,Fizz,22,23,Fizz,Buzz,26,Fizz and so on depending on 'stop' in the If-statement.


Solution

  • Valentins comment is correct, you do need to add brackets around your loop. You are however also redefining the string var in every iteration of the loop.

    The last if also makes the output a bit wrong as for example 15 would hit all 3 statements and print FizzBuzzFizzBuzz

    so go with something like

    var fizzbuzz = function(start,stop) {
      var string = '';
      var addComma = false;
      for (var x=1;x <= stop; x++){
        addComma = false;
        if (x%3 == 0) {
            string += 'Fizz';
            addComma = true;
        }
        if (x%5 ==  0){
            string += 'Buzz';
            addComma = true;
        }
        if(addComma && x!== stop){
            string+=','
        }
      }
      return string;
    };
    

    This is not the best way to keep track of where to add a comma, but it does the job.