I'd like to see if this is a reasonable solution, or is just plain terrible.
I wouldn't say it is "terrible" - mostly because it works and doesn't appear to be very inefficient. However, 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. - Reduce mathematical operations Instead of setting the value in each case, append to
output, which allows one to eliminate the first conditional, as well as theelsekeywords and then ifoutputis still an empty string, set it toiusing short-circuiting boolean 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...
- Statements and blocks - 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.
###Updated Code Consider the modified code below, utilizing the feedback above. Try a comparison in this jsperf. Generally the code below is more performant but in certain browsers results varied.
Note: the inline console in the snippets is truncated to ~50 lines, but the complete console log should be visible in your browser console.
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);
}