I’m currently taking the code academy course on Javascript and I’m stuck on the FizzBuzz task. I need to count from 1-20 and if the number is divisible by 3 print fizz, by 5 print buzz, by both print fizzbuzz, else just print the number. I was able to do it with if/ else if statements, but I wanted to try it with switch statements, and cannot get it. My console just logs the default and prints 1-20. Any suggestions?
for (var x = 0; x<=20; x++){ switch(x){ case x%3==0: console.log("Fizz"); break; case x%5===0: console.log("Buzz"); break; case x%5===0 && x%3==0: console.log("FizzBuzz"); break; default: console.log(x); break; }; };
Advertisement
Answer
Switch matches the x in switch(x){ to the result of evaluating the case expressions. since all your cases will result in true /false there is no match and hence default is executed always.
now using switch for your problem is not recommended because in case of too many expressions there may be multiple true outputs thus giving us unexpected results. But if you are hell bent on it :
for (var x = 0; x <= 20; x++) { switch (true) { case (x % 5 === 0 && x % 3 === 0): console.log("FizzBuzz"); break; case x % 3 === 0: console.log("Fizz"); break; case x % 5 === 0: console.log("Buzz"); break; default: console.log(x); break; }
}