Why add if/else statements to a case?


#1

Hello, I am trying to understand the logic behind adding if/else statements to cases as requested by the assignment. If the code asks for a "prompt" it only allows 1 entry, how can it check for multiple conditions? Also in a realistic coding situation where could this be helpful? Thanks in advance for any response.

Add some if/else statements to your cases that check to see whether one condition and another condition are true, as well as whether one condition or another condition are true. Use && and || at least one time each.

Here is my code for a simple Batman "Code your own adventure"

var user = prompt("The time has come to pass the torch.. What is your name?").toUpperCase();
switch(user) {
case 'JASON':
console.log("Jason Todd? Interesting");
break;
case 'DICK':
console.log("Are you related to the greyson family?");
break;
case 'ROBIN':
console.log("Already a sidekick?");
break;
default:
console.log("I'm sorry.. you dont posess the necessary skils..Alfred will see you out...");
}


#2

Obviously adding an IF-condition in this particular exercise makes no sense. We only have 1 prompt and we already use the switch and its cases to check for possible answers. An IF-condition would only make sense if we have at least 1 other prompt so that we can use a condition to check if a certain answer/input was given to the 2nd prompt.

For example, you use the first prompt and the switch to check for the first name (as you did). But you could add a 2nd prompt which asks for the family name and then you use an IF-condition inside the case to check for a certain last name.

I have to admit that this exercise can be a bit confusing. This question has popped up many times in the forum. It might have been better to just tell the users to add another prompt for this exercise to make sense. However I also understand that for the sole purpose of showing how "&&" and "||" work this is a feasable way.


#3

Thanks, to me it seemed like adding the IF statement was weird, but I wasn't certain. Thank you for taking the time to explain it to me and help me understand it.


#4

So the logic you have written about makes complete sense. That said there does not seem a way around if you don't put in the if else statements. Is the only way around this to actually create a second prompt and place some if else statement in the code? Here is what I have so far:

var user = prompt("You decide to go on a trip. Would you rather drive, ride a train, or fly?").toUpperCase();

switch(user){
case 'FLY':
console.log("Good choice. Flying will get you there much faster.");
break;
case 'TRAIN':
console.log("This is a great way to see the country and relax at the same time. All Aboard!");
break;
case 'DRIVE':
console.log("Looks like you have control of this trip. Don't pick up hitch hikers.");
break;
default:
console.log("You better choose again. You wont get anywhere that way.");
}