Using the 'or' operator in switch cases?


#1

I know this is very basic switch javascript but just an example to demonstrate what I want to achieve.
For example I want the console.log to return the message whether the user types either the player with or without the capital letter in the name.
The 'or' operator: || doesn't seem to work. How can I get this to work? Thanks!

var answer = prompt("Who is your favourite footballer? Type your answer here (surname only)");

switch(answer) {
  case 'Messi' || 'messi':
    console.log("Messi is a footballing hero.");
    break;
  case 'Ronaldo' || 'ronaldo':
    console.log("Ronaldo is a top class athlete.");
    break;
    case 'Sanchez' || 'sanchez':
    console.log("Sanchez is a work horse with technique!");
    break;
    default:
    console.log("Please enter a footballers name!");
}

#2

I've found that this works, creating 2 cases for the same console log:

switch(answer) {
  case 'Messi':
      break;
  case 'messi':
    console.log("Messi is a footballing hero.");
    break;

Is there an easier or more efficient way of doing it?


#3

just convert the user input to lowercase? then you cover all possible cases at once


#4

Thanks, I haven't seen that done before I'm still at a fairly beginner stage in learning javascript, how would it be done if you wouldn't mind showing me?


#5

toLowerCase() has been covered, i am 100% sure. here is a documentation page about to lowercase


#6

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