Home > database >  Javascript switch case with multiple expression
Javascript switch case with multiple expression

Time:10-16

I currently attempted to write a switch case taking in 3 variables

switch (user.nameInDB === userInputMobile,
        user.phoneInDB === userNumberInputMobile,
        user.emailInDB === userInputFrontend) {
   case ( true, _, _) :
      // Do something
   case ( _, true, _) :
      // Do something else
   case ( _, _, true) :
      // Do last thing
   default:
     break;
   }

I have ran into an error where the " _ " is not defined. Any advise on how to organise this?

enter image description here

CodePudding user response:

If you're only checking for one variable at a time or maybe even more I recommend using If statments instead, It improves code readability and also has better performance than checking for multiple variables that aren't required to checked.

if (user.nameInDB === userInputMobile) {
   // do something
} 

However, If you wish to use switch statments you could just pass undefined, null or true/false depending on your use case.

CodePudding user response:

As per the doc, switch statement evaluates an expression. So what you are trying to achieve

switch (expression1, expression2, expression3, ...)

Is the wrong way.

If you want to use switch for the same thing, you can use

const _ = false
const expression = [true, false, false].join()

switch(expression){
   case [true, _, _].join(): 
   // Do something
   case [_, true, _].join(): 
   // Do something
   case [_, _, true].join(): 
   // Do something
   default: 
   // Do something
}
  • Related