0
var output = []; 
var count = 1;

function fizzBuzz() {

    if (count % 5 === 0 && count % 3 === 0) {
        output.push("FizzBuzz");
    } else if (count % 5 === 0) {
        output.push("Buzz");
    } else if (count % 3 === 0) {
        output.push("Fizz");
    } else {
        output.push(count++;);
      
    }
//count++;//
    
  console.log(output);
    
}

count++ does not work in else statement. How ever if I take it out from else statement and put count into else it works. Why is the reason?

  • 2
    `count++` is using the **postfix** operator, meaning it increments the variable after the statement runs. – Heretic Monkey Dec 30 '22 at 13:46
  • Does this answer your question? [Atypical uses for Javascript's ++ and -- operators](https://stackoverflow.com/questions/8058818/atypical-uses-for-javascripts-and-operators) – Heretic Monkey Dec 30 '22 at 13:50

1 Answers1

1

To fix the bug, you can simply move the count++; statement to the end of the function, like this:

function fizzBuzz() {
if (count % 5 === 0 && count % 3 === 0) {
    output.push("FizzBuzz");
} else if (count % 5 === 0) {
    output.push("Buzz");
} else if (count % 3 === 0) {
    output.push("Fizz");
} else {
    output.push(count);
}
count++;
console.log(output);}

There is a bug in the code that is causing the count variable to not be incremented at the end of each iteration. This means that the function will only ever process the first number and then stop.