Skip to main content
2 of 21
update explanation and add links

I'd like to see if this is a reasonable solution, or is just plain terrible.

I wouldn't say it isn't "terrible" - mostly because it works and doesn't appear to be very inefficient. There are some improvements that can be made.

  • use strict equality comparison - i.e. === when comparing values. That way it won't need to convert the types.
  • Instead of setting the value in each case, append to output, which allows one to eliminate the first conditional, as well as the else keywords and then if output is still an empty string, set it to i using short-circuiting logic. That way there will only be two modulus division operations instead of three.
  • Use consistent indentation for readability. Maybe it was the case that your code was indented properly but when you pasted here it was thrown off because of the markdown formatting...
  • expand blocks so each statement is on a separate line and terminated with a semi-colon. While Automatic semicolon insertion can be useful it is wise not to depend on it.

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

    if (i % 3 === 0) {
        output += "Fizz";
    }
    if (i % 5 === 0) {
        output += "Buzz";
    }
    output = output || i;

    console.log(output);
}

Try comparison in this jsperf.