Zen and the Art of FizzBuzz Maintenance

Given that @felgall and I took a slight diversion off topic on @sorin21us’s thread on Can jQuery do everything that JavaScript is doing, too?, I thought I’d start a separate thread to post my code for a fizzbuzz solution. My JS knowledge is the result of a bit of learning from books, which I never get far with, and a two day course I did in September. The first piece of code was my own creation after day 1. The other two versions came from the instructor if I remember rightly. All of them work in the console.

My version

for (var i = 1; i <= 100; i++) {
  var response = i;
  if ((response % 3 == 0) && (response % 5 == 0) == true) {
    response = "FizzBuzz";
    console.log(response);
  } else if (response % 3 == 0) {
    response = "Fizz";
    console.log(response);
  } else if (response % 5 == 0) {
    response = "Buzz";
    console.log(response);
  } else {
    console.log(response);
  }
};

Instructors version(s)

for (var i = 1; i <= 100; i++) {
  
  if ((i % 3 == 0) && (i % 5 == 0) == true) {
    console.log("FizzBuzz");
  } else if (i % 3 == 0) {
    console.log("Fizz");
  } else if (i % 5 == 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
};

and…

for (var i = 1; i <= 100; i++) {
  var output = ""
  if (!(i % 3)) {output += "Fizz"}
  if (!(i % 5)) {output += "Buzz"}
  console.log(output || i);
}

Lastly, here’s an interesting take on it posted last month The Wrong FizzBuzz

What does your look like?

This solution worked on the test site http://rileyjshaw.com/challenger/

function fizzbuzz (n) {
  var res=(n%3==0 && n%5==0)? "FizzBuzz": (n%3==0)? "Fizz": (n%5==0)? "Buzz": n; return res;
}

So even your instructor didn’t know how to write it properly and used an extra if statement that wasn’t necessary and which would become three extra if statements if one extra condition was added.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.