# FizzBuzz in Javascript

I'm sure everyone here knows what FizzBuzz is. I would like constructive criticism for my solution.

I'm a beginner to programming as a whole and this isn't my first solution, but it's what I think is my best solution. I'd like to see if this is a reasonable solution, or is just plain terrible.

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

if(i % 15 == 0) {output = "FizzBuzz"}
else if(i % 3 == 0) {output = "Fizz"}
else if(i % 5 == 0) {output = "Buzz"}
else {output = i;}

console.log(output);
}


The output is correct. It's your standard FizzBuzz output.

• It's hard to give constructive criticism on such a small, simple function. It's a reasonable solution and the only things I could pick out being wrong would be me being extremely picky or a personal preference. Commented Jan 8, 2019 at 15:36
• You could go with var output = i; and then remove that final else block.
– user189829
Commented Jan 8, 2019 at 15:37
• One possible issue is you are relying on a standard fizzbuzz using 3 and 5 (hence checking for 3 * 5 as 15). Someone might give you a test using 2 and 4 to see if you fell into the trap of checking for 8. Commented Jan 9, 2019 at 10:39
• It would be better to include the actual spec you are following. The FizzBuzz solution looks fine. Any extra points goes to how you follow the nuance of the spec. If you really wanted to get fancy, you could do it without the explicit "FizzBuzz" part of the algorithm. Commented Jan 9, 2019 at 14:39
• This question is being discussed on meta. Commented Jan 25, 2019 at 17:45

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.

• Style Guide Consider following a style guide. Many common style guides advise separating keywords with a space - e.g. if ( instead of if(.

• Use consistent indentation The first and last lines within the for loop are not indented, while the other lines between them are, though 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...

• Abstract logic into a function As Paul's answer suggests: you can put the core logic into a function that returns the output but doesn't handle outputting the value (e.g. to the console). This allows such code to be atomic and testable - congruent with the Single Responsibility Principle. Also, the return statement can eliminate the need for else keywords within a function. One drawback is that calling a function on each iteration may slow down operations but should be negligible for a set of numbers 1 through 100.

### Updated Code

Consider the modified code below, utilizing the feedback above. I also used this code in the code contained in my recent question: Fizzbuzz with dynamic height container

Note: the inline console in the snippets is truncated to ~50 lines, but the complete console log should be visible in your browser console.

function fizzBuzz(value) {
if (value % 15 === 0) { return "FizzBuzz"; }
if (value % 3 === 0) { return "Fizz"; }
if (value % 5 === 0) { return "Buzz"; }
return value;
}
for (let i = 1; i <= 100; i++) {
console.log(fizzBuzz(i));
}

One option I did consider is to minimize the number of modulo operations, append to the output string instead of outputting it. If you are trying to optimize for speed, this might not be the approach to take because appending to the string may be much slower than doing an extra couple modulo operations. Try a comparison in this jsPerf test.

function fizzBuzz(value) {
let output = "";
if (value % 3 === 0) { output += "Fizz"; }
if (value % 5 === 0) { output += "Buzz"; }
return output || value;
}
for (let i = 1; i <= 100; i++) {
console.log(fizzBuzz(i));
}

• There is also the "never use semicolons" school. blog.izs.me/2010/12/… feross.org/never-use-semicolons Commented Jan 8, 2019 at 22:01
• @CaseyB I don't think arguing about micro-optimizations like this when OP is a beginner is a good idea at all.
– user179245
Commented Jan 9, 2019 at 9:43
• @Voile One million percent. Even if this were a production-ready, enterprise-grade, cloud-based microservice™, readability and maintainability is always the number one concern. The concept of micro-optimizing a JavaScript FizzBuzz is honestly hilarious. Commented Jan 9, 2019 at 10:34
• @Michael FizzBuzz Enterprise Edition begs to differ. :P But FWIW, I believe Casey was merely providing a counterargument for the microoptimization that the answer itself first suggested. Commented Jan 9, 2019 at 12:05
• @MateenUlhaq 260 issues... man, they really need to refactor it, arrange UATs, and use Kanban. Commented Jan 9, 2019 at 13:10

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);
}

(I've fixed a few other things as suggested in Sam's answer)

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

• @PatrickRoberts True. I wanted to focus more on the approach to solving the problem than those things. Buuut I did correct everything else (I couldn't help myself) so yeah I've made that change as well. Thanks Commented Jan 10, 2019 at 16:15
• You forgot the equality in the ternary expression. I tried to edit myself but I can only make edits of at least 6 characters :| Commented Jan 10, 2019 at 16:23
• You're not wrong about the repetition of 3, 5 ,Fizz and Buzz, but you're biased on how to improve it. Consider a change where "FizzBuzz" now needs to be on a multiple of 13. Or a change where the multiple of 15 needs to be "Floopidoops". In these cases, OP's code is much easier to change than yours is. The issue here is whether you infer that the relationship between the multiples (3, 5, 15) , and the relationship between "Fizz", "Buzz" and "FizzBuzz", is causal or coincidental. It requires elaboration (= analysis) before you can make the right judgment call. Commented Nov 20, 2019 at 14:43

I think it's fine as is, though some folks like to return early instead of using a series of if..else. For example:

function calc(i) {
if(i % 15 == 0) return "FizzBuzz";
if(i % 3 == 0) return "Fizz";
if(i % 5 == 0) return "Buzz";
return i;
}

for(var i=1;i<=100;i++) {
console.log(calc(i));
}

• "Returning early" is often called "multiple exit points" and is sometimes considered poor practice. Commented Jan 9, 2019 at 18:59
• "Returning early" is often called "validation" and is often considered good practice. Commented Jan 10, 2019 at 11:22
• Returning early has many names and people get very worked up about whether their way is best. Commented Jan 10, 2019 at 17:25
• @MobyDisk That advice is originally from Assembly, and referred to "places to exit to", not "places to exit from". That removes the "it's always been done this way, so there must've been a reason" argument. Before applying your revised version of this advice to a particular scenario, check whether it actually makes sense. In this case, it doesn't. Commented Jan 12, 2019 at 12:44

Expanding on Michael's answer, you could also create an object with all the words you want, with the key being the number your input must be divisible by, to make this more dynamic and a bit more future proof (A lot easier to add a new entry to the object versus adding more lines of code), and the object itself can also be dynamically generated.

divisions = {3: "Fizz", 5: "Buzz", 7: "Jazz"};

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

for (var x in divisions) {
if(i % x == 0) output += divisions[x];
}

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

• How do you guarantee that Fizz always comes before Buzz? Unlike in PHP, in JavaScript the keys of an object are not in a deterministic order. Commented Nov 20, 2019 at 1:37
• @RolandIllig: With a change to the data structure, divisions.sort(d => d.Value) (or any variation thereof) fixes that. Commented Nov 20, 2019 at 14:48
• @Flater yep, I know that. I wanted to hear exactly that from Grumpy, since the answer is wrong in its current state. Commented Nov 20, 2019 at 18:56
• @RolandIllig I'm sorry, I don't really understand what you are asking. Commented Dec 2, 2019 at 14:29
• Your code only works if the divisors and words are to be applied in order. In general, the order of the words is not specified. Therefore your code works "by accident", not by design. Commented Dec 2, 2019 at 18:10

I tend to be somewhat "literalist", at least at first, when implementing algorithms. So I would start with this, and then optimize from there. I like that it keeps things very clear.

const calcFizzBuzz = function(num) {
let result = "";
if (num % 3 === 0) {
result += "Fizz";
if (num % 5 === 0) {
result += "Buzz";
}
}
else if (num % 5 === 0) {
result += "Buzz";
}
else {
result = num;
}
return result;
}

for (let i = 0; i < 100; i++) {
console.log(calcFizzBuzz(i));
}

• The repeated if (num % 5 === 0) { result += "Buzz" } is obviously redundant. Why do you prefer to write it this way? Commented Nov 20, 2019 at 1:43

From a maintenance stand point, I think it's better that you check for 3 and 5 instead of checking for 15. The issue with checking for 15 is that when you come back to your code 6 months from now, you won't realize that you were just printing fizzbuzz when something was divisible by both 3 and 5. That might matter in the future, but I think that's something worth talking about in an interview.

Though your code is fine, another thing to look is amount of division happening the code, Division is computationally expensive operation and as @Michael has suggested that it is redundant. So always try to minimise the multiplication and division operation in your code.

You have mentioned that you are a beginner programmer. I believe it is a good practice to start familiarising your self with topics like Computational Complexity.

Look here for computational complexity of mathematical functions

• While I think it's a bit early for a beginning programmer to be learning about things such as memory management (assuming this is one of their FIRST actual programs), I think this is a good answer! Commented Jan 9, 2019 at 20:10
• This advice screams "premature optimization". Division is not an expensive operation. It's a bit more expensive that addition but it's not really expensive on today's computers. Your mobile phone can do millions of divisions in a fraction of a second. String concatenation is much more expensive, by far. The most important metric in code quality is readability. Also, if you are talking about computational complexity, you should note that your change won't change complexity at all. Commented Jan 9, 2019 at 23:37
• The theoretical computational complexity of the underlying division algorithm is practically irrelevant. Commented Jan 10, 2019 at 3:05
• @Sulthan The subject computational complexity doesn't take in to account how many operations a machine can perform, it takes into account how many operations/steps are required to solve a problem. While CC of addition i linear, division is quadratic. Dividing only by 3 and 5 would change the complexity and results of those can be saved in a bool variable which can be evaluated in constant time complexity. Commented Jan 10, 2019 at 13:58
• On a modern CPU integer division takes 1 CPU cycle, the JS version of % a little longer. JS will use 32bit signed ints when it can so the operation is insignificant in comparison to just calling a function. BTW the linked computational complexity page has nothing to do with how CPUs ALU and FLU process the basic math operations. Commented Jan 10, 2019 at 14:08