-1

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);
cdlane
  • 40,441
  • 5
  • 32
  • 81
  • 1
    That is not the correct syntax of `switch/case`: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch – musically_ut Feb 05 '16 at 23:12
  • To be specific, `case` only accepts values to compare against the expression in the `switch` clause. You cannot dynamically evaluate the `case`'s value like this. – Robert Rossmann Feb 05 '16 at 23:16

3 Answers3

3

check how you're using the switch statement: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch

in the switch line x is your expression and ((x%5) == 0) is your value. I think what you mean to do is a handful of if/else statements.

Kevin
  • 54
  • 3
0

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;
}
Hatchet
  • 5,320
  • 1
  • 30
  • 42
0

You are trying to match the value of x with expressions whose values are either true or false. You can pass true in the switch and the switch will "match" with the first case statement that evaluates as true.

While this sort-a works, I would recommend just doing if/else statements. This won't work for number 30 which is both True for X%3 and x%5. It will match with the x%3 first and stop there.

printOut = ""; 

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


  switch(true) {

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

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

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

  }

                             }
console.log(printOut);
SlaterCodes
  • 1,139
  • 10
  • 21