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.
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.