Switch and case, ( case '>7' : ) ? is it possible?


#1
// Write your code below!
var answer=prompt("How much kids do you have?");
switch(answer) {
    case'1':
    console.log("Quality before quantity!");
    break;
     case'2':
    console.log("1 is good, but 2 is better right!");
    break;
     case'3':
    console.log("couldn't end on a tie?");
    break;
     case'4':
    console.log("I guess you like even numbers!");
    break;
     case'5':
    console.log("At least you can still count them on one hand!");
    break;
     case'6':
    console.log("Do you remember all their birthdays?");
    break;
     case'7':
    console.log("Do you remember all their names?");
    break;
     case '8':
    console.log("You trying to break a record!?");
    break;
    default:
    console.log("sorry I did not understand your answer, please try again?");
    
    }

This block passes the exercise. But originally I wanted to make case '8' : like this -> case '>7' : . so that any NUMBER >7 would log that string.. But I couldn't figure it out. anyone knows how ?

also for the default case, is there a way to repeat the switch when the default case is activated ? (restart the switch..) ??

thanks for your help.


#2

I do not think it's possible to write multiple numbers as a case, ( I may be wrong) so I suggest to put a saying to what to put. Like:

var answer = prompt("What's the creepiest thing you know?","Say it here!");

If you try copy + pasting this into your code and look at what it happens, you can see that inside where you put the answer, you can see the words "Say it here!". That's because you put another string after the comma, and that functions as that. So I suggest to put in there to put numbers 1, 2, 3, 4, 5, 6, 7, and 8~ if it is greater or is 8. Then change your case to 8~ and it should work.

Remember to put the 1, 2, 3, 4, 5, 6, 7, and 8~ the way I put "Say it here!".:smiley:


#3

I would think of two ways of doing this. One way is to use a boolean after switch e.g.

switch(true){
    case answer ===1: ...; break;
    ...
    case answer > 8: ... 
}

this would allow you to use conditions as your cases which are picked if they are well true. And the other way is to just not use break;

e.g.

...
case "7":
case "8":
    here goes your code; break;

Now if you pick case 7 you execute it (in this case there is nothing to execute) and because you have no break you go on with the next case (this rare time on purpose) this let's you combine several cases.

And for a repetition well you could wrap your switch in a loop or function:

repeat = true;
while(repeat){
     ...
     switch(answer){
     case "1": ...; repeat = false;break;
     ...
     default: anything just leave repeat true

}

or with a function

var runAgain = function(){
    switch(answer){
    ....
    default:
      console.log()
      runAgain();
    }
} 
runAgain();