Why is this FizzBuzz switch statement not working?

Hi!
I thought I’d do the Fizz Buzz lesson using a switch - case statement but I’m getting undefined returned.
Can anyone tell me what I’m missing here?
Thank you ahead of time!!

function fizzBuz(input) {
  switch (input) {
    case typeof input !== "number":
      // case !Number.isInteger(input):
      console.log("Not a number");
      break;
    case input % 3 === 0 && input % 5 === 0:
      console.log("FizzBuzz");
      break;
    case input % 3 === 0:
      console.log("Fizz");
      break;

    case input % 5 === 0:
      console.log("Buzz");

    case input % 3 !== 0 && input % 5 !== 0:
      console.log(`Neither! input is ${input}`);
    default:
      break;
  }
}

console.log(fizzBuz(8)); // undefined
1 Like

The problem here is that a void function return value is used (you’re not technically returning anything from this function).

Calling of such functions always produces an undefined value and such assignment may indicate an error.

You have the right idea for sure though. But I would say a few modifications to your code can be made here to make this work if you are insistent on keeping your switch statement.

function fizzBuz(input) {
    switch (true) {
        case typeof input !== "number":
            // case !Number.isInteger(input):
            return "Not a number";

        case input % 3 === 0 && input % 5 === 0:
            return "FizzBuzz";

        case input % 3 === 0:
            return "Fizz";

        case input % 5 === 0:
            return "Buzz";

        default:
            return `Neither! input is ${input.toString()}`;
    }
}

console.log(fizzBuz(5));

In the modified code above, we now allow this function to always return the string instead of console.log-ing the output. This gives your function a return value other than void which will allow your output to be shown using console.log()

We also set the switch statement’s expression to true so that it will always run since you’re already handling the expressions in your case clauses.

I removed the last case clause and set it as your default value and also added a break statement to your second to last case clause to avoid fall-through. - (see MDN docs here for JavaScript Switch)


I hope this clears things up for you and gives you your answer :slight_smile:

Thank you so much for the detailed reply!
There are more than a couple learning points for me in this.
Greatly appreciated!!!

Hi,

I must admit I do not understand this behaviour.

I did try OP code and I am surprised to see the last case is ignored in favour of the default clause.

As you can see in the watch, the expression in that case is true. So why it is ignored ?

I even added a new case explicitely checking input === 8 and it is also ignored.