7
votes

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


};
8
Switch (true) not switch (x) - Albert Renshaw
Case compares the case to the value you are switching. You currently check if {x%3==0}==x you want to check if {x%3==0}==true. Also you use === instead of == a few times - Albert Renshaw

8 Answers

10
votes

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

}

2
votes

I thought switch too,but no need.

    for (var n = 1; n <= 100; n++) {
  var output = "";  
  if (n % 3 == 0)
    output = "Fizz";
  if (n % 5 == 0)
    output += "Buzz";
  console.log(output || n);
}
1
votes

Switch statement checks if the situation given in the cases matches the switch expression. What your code does is to compare whether x divided by 3 or 5 is equal to x which is always false and therefore the default is always executed. If you really want to use a switch statement here is one way you can do.

for (var i=1; i<=30; i++){
  switch(0){
    case (i % 15):
      console.log("fizzbuzz");
      break;
    case (i % 3):
      console.log("fizz");
      break;
    case (i % 5):
      console.log("buzz");
      break;
    default:
      console.log(i);
  }
}
0
votes

Not to too my own horn but this is much cleaner:

var numbers = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
for (var i = 1; i <= numbers.length; i++) {  
    if (i % 15 === 0) {
        console.log("FizzBuzz");
    } else if (i % 5 === 0) {
        console.log("Buzz");
    } else if (i % 3 === 0) {
        console.log("Fizz");
    } else {
        console.log(i);
    }
};
0
votes

The switch(true) part of this statement helped me. I was trying to do a switch statement for fizzbuzz. My solution incorporates the coding style of Rosettacodes - general solution. Most significantly the use of force typing to shorten the primary conditionals. I thought, it was valuable enough to post:

var fizzBuzzSwitch = function() {
  for (var i =0; i < 101; i++){
    switch(true) {
      case ( !(i % 3) && !(i % 5) ):
        console.log('FizzBuzz');
        break;
      case ( !(i % 3) ):
        console.log('Fizz');
        break;
      case ( !(i % 5) ):
       console.log('Buzz');
       break;
      default:
       console.log(i);
    }
  }
}
0
votes

Here's what made it clear for me, might help : It's a misinterpretation of what switch (x){} means.

It doesn't mean : "whenever whatever I put inbetween those brackets is true, when the value of x changes."
It means : "whenever x EQUALS what I put between those brackets"

So, in our case, x NEVER equals x%3===0 or any of the other cases, that doesn't even mean anything. x just equals x all the time. That's why the machine just ignores the instruction. You are not redefining x with the switch function. And what you put inbetween the brackets describes x and x only, not anything related to x.

In short :
With if/else you can describe any condition.
With switch you can only describe the different values taken by the variable x.

0
votes

Here's a solution incorporating @CarLuvr88's answer and a switch on 0:

let fizzBuzz = function(min, max){
  for(let i = min; i <= max; i++){
    switch(0){
      case i % 15 : console.log('FizzBuzz'); break;
      case i % 3  : console.log('Fizz'); break;
      case i % 5  : console.log('Buzz'); break;
      default     : console.log(i); break;
    }
  }
}

fizzBuzz(1,20)
0
votes

We can use a function to find a multiple of any number and declare two variables to identify these multiples so that if you want to change the multiples you only need to change at max 2 lines of code

function isMultiple(num, mod) {
    return num % mod === 0;
}
let a = 3;
let b = 5;
for(i=0;i<=100;i++){
    switch(true){
        case isMultiple(i,a) && isMultiple(i,b):
            console.log("FizzBuzz")
        case isMultiple(i,a):
            console.log("Fizz");
        case isMultiple(i,b):
            console.log("Buzz");
        default:
            console.log(i);
    }
}