0

Can't seem to point out something obvious. This solution doesn't work. Please help?

FizzBuzz question: Print numbers from 1 to 100. Print Fizz instead of numbers divisible by 3. Print Buzz instead of numbers divisible by 5. Print FizzBuzz instead of numbers divisible by both 3 and 5.

for(var i = 1; i <= 100; i++) {
 
 switch (i) {

      case (i%3 === 0 && i%5 === 0):
        console.log('FizzBuzz'); 
        break;

      case (i%3 === 0):
        console.log('Fizz');
        break;

      case (i%5 === 0):
        console.log('Buzz');
        break;

      default:
        console.log(i);

 }
    }
Gary
  • 13,303
  • 18
  • 49
  • 71
Karma
  • 2,196
  • 1
  • 22
  • 30

3 Answers3

3

The problem is, you are switching on the value of variable i. Then you are comparing that with expressions like i % 3 === 0, so the comparison becomes i === (i % 3 === 0).

Instead, you can switch on true, so any expression evaluating to true will be switched into.

for (var i = 1; i <= 100; i++) {
  switch (true) {
    case (i % 3 === 0 && i % 5 === 0):
      console.log('FizzBuzz');
      break;

    case (i % 3 === 0):
      console.log('Fizz');
      break;

    case (i % 5 === 0):
      console.log('Buzz');
      break;

    default:
      console.log(i);
  }
}
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
1

A switch enters the branch if the case matches the value you are switching for, therefore:

  switch (i) {
    case (i%3 === 0 && i%5 === 0):

Will enter the first case if:

 i === (i%3 === 0 && i%5 === 0)

E.g. for 15 it will be:

 15 === true // -> false

so it wont enter the branch. Therefore instead of switching for i you have to switch for true:

  switch(true) {
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
-3

Did you try not to break the switch, because when it matches it won't print the other stuff it is supposed to? Maybe?