Search code examples
javascriptfizzbuzz

Why no fizzbuzz being printed out?


This is my code. I am not getting any Fizz buzz printed. I am only getting numbers. Could anyone explain why? Thanks

printOut = ""; 

for (var x=1; x < 101 ; x++) {


  switch(x) {

      case((x%3) == 0):
      printOut+="\n"+ "Fizz" ;
      break;

      case((x%5) == 0):
      printOut+="\nBuzz";
      break;

      default:
      printOut+="\n" + x ;
      break;

  }

}
console.log(printOut);

Solution

  • You're using the switch statement improperly. Each case (value): is basically supposed to be run whenever x equals value.

    To solve this problem, simply remove the switch statement entirely, and substitute ifs for each case:

    for (var x = 1; x < 101; x++) {
        if ((x % 3) == 0)
            printOut += "\n" + "Fizz";
        else if ((x % 5) == 0)
            printOut += "\nBuzz";
        else
            printOut += "\n" + x;
    }