Switch Always Returns Default


#1


https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/1/4?curriculum_id=506324b3a7dffd00020bf661#


This code always gives the default answer. What's wrong with it?


var number = prompt("What's your favorite number?");

switch(number) {
    case (number % 2 === 0):
        console.log("I like even numbers too!");
        break;
    case (number % 2 === 1):
        console.log("I don't like odd numbers. They're a little off.");
        break;
    case isNaN(number):
        console.log("You can't have " + number + " be your favorite number. It's not even a number!");
        break;
    default:
        console.log("Are you sure? I prefer whole numbers myself.");
}


#2

Nevermind. I figured out why it's wrong, but I still don't know how to make it work.


#3

Your switch is checking the value of number and comparing that to the various cases you have. Your cases, however are expressions that produce booleans so they will not match your number ever.

Also, this is hard because, if I'm getting the right link, your exercise is asking for 3 cases but whether a number is even or odd presents only two logical cases. Checking isNaN is a good idea but generally you would check for valid input separately from your actual logic.

var number = prompt("Gimme a number, fool!");

if (isNaN(number)) {
  console.log("Are you taking this seriously?");

} else {
  switch(...) {
    // cases
  }
}

#4

The problem I found is that the prompt will always give a string for an answer. If you put in 42, the computer thinks, "42." However, isNaN is generous, and will correct "42" to 42. So it fails to be even because it's a string, then it fails to be odd because it's a string, then it fails to be not a number because isNaN thinks " oh he probably meant 42, so it is a number," leaving only the final option. So what I would need for this to work is to first check if it's a number, then extract the number from the string and put that through the even/odd test. The problem is I don't know how to make it take the string containing a number and turn it into the number.


#5

I found the answer. If you type eval("42"), the output will be 42.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.