javascript fizzbuzz switch statement
Asked Answered
S

9

9

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


};
Shreveport answered 24/9, 2014 at 14:42 Comment(2)
Switch (true) not switch (x)Engelhardt
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 timesEngelhardt
V
11

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

}

Vtarj answered 24/9, 2014 at 14:52 Comment(3)
That is horrible code, if I encountered it, I would refactor it :DMelano
I upvoted both the question and answer as it helped me - specifically the switch(true) - but I agree with @Melano with the refactor point. Initial reaction was spacing - and ran across force typing conditionals that rosetta code did liked the succinctness - posted an answer below : - ?Sf
More optimized: Remove top case and remove break in mod3 case. >:)Engelhardt
B
2

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);
}
Buenrostro answered 7/2, 2017 at 10:59 Comment(1)
I love this solution, really clean.Farias
S
2

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);
  }
}
Spatial answered 30/4, 2020 at 19:47 Comment(1)
This is actually beautiful. Nice!Maudmaude
D
0

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);
    }
};
Diaphane answered 25/2, 2015 at 20:46 Comment(0)
S
0

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);
    }
  }
}
Sf answered 17/5, 2015 at 1:10 Comment(0)
M
0

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.

Maryn answered 28/1, 2018 at 5:25 Comment(0)
Y
0

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)
Yi answered 4/5, 2018 at 20:57 Comment(0)
N
0

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);
    }
}
Naara answered 9/8, 2020 at 23:2 Comment(0)
M
0

In typescript it can be done as follow:

const range = (startingNumber: number, endingNumber: number): number[] =>
  Array.from({ length: endingNumber - startingNumber + 1 }, (_, index) => startingNumber + index);

const isDivisibleBy = (input: number, divisor: number): boolean => input % divisor === 0;

const fizzBuzzOutput = (input: number): string =>
  isDivisibleBy(input, 3) && isDivisibleBy(input, 5)
    ? "FizzBuzz"
    : isDivisibleBy(input, 3)
    ? "Fizz"
    : isDivisibleBy(input, 5)
    ? "Buzz"
    : input.toString();

const fizzBuzz = (startingNumber: number, endingNumber: number): string[] =>
  range(startingNumber, endingNumber).map(fizzBuzzOutput);

const answer = fizzBuzz(1, 20);
console.log(answer);
Minutely answered 28/11, 2023 at 21:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.