Skip to main content
1 of 5
Michael
  • 778
  • 4
  • 11

One of the problems is that the case where you check i % 15 (i.e. i is a multiple of 3 and 5) is unnecessary. You have the concept of 3 and 5 repeated, and the concept of Fizz and Buzz repeated.

This is not currently much of a problem but suppose someone asks you to extend your program to print "Jazz" when i is a multiple of 7. Using your current strategy we now need a case where i is a multiple of:

  1. 3
  2. 5
  3. 7
  4. 3 and 5
  5. 3 and 7
  6. 5 and 7
  7. 3 and 5 and 7

It would look something like this:

for(var i = 1;i <= 100; i++) {
    var output = "";

    if(i % 105 == 0) {output = "FizzBuzzJazz"}
    else if(i % 15 == 0) {output = "FizzBuzz"}
    else if(i % 35 == 0) {output = "BuzzJazz"}
    else if(i % 21 == 0) {output = "FizzJazz"}
    else if(i % 3 == 0) {output = "Fizz"}
    else if(i % 5 == 0) {output = "Buzz"}
    else if(i % 7 == 0) {output = "Jazz"}
    else { output = i; }

    console.log(output);
}

See how quickly that got out of hand? If we add a fourth word it becomes even worse.

If we use a different strategy by appending text to the output variable, we can get away with having as few conditions as we have words.

for(var i = 1; i <= 100; i++) {
    var output = "";
    if (i % 3 == 0) {output += "Fizz"}
    if (i % 5 == 0) {output += "Buzz"}
    if (i % 7 == 0) {output += "Jazz"}

    console.log(output == "" ? i : output);
}

On thing that might be new to you here, if you're a beginner, is that the expression used as the argument for console.log or called the conditional or ternary operator. Ours says that if the output is blank (i.e. not a multiple of 3, 5 or 7) then print i, else print the string that we've compounded.

The ternary operator can always be replaced by an if-statement if you're not yet comfortable with it.

Michael
  • 778
  • 4
  • 11