0

I want to check if a variable (in this case sampleVariable) is equal to THIS or THAT:

if(sampleVariable == "THIS" || chosenVerb == "THAT")

The above code should work fine, but I was wondering if there was a way to simplify and compact it - for example, something like this (this probably isn't how you do it, just an example):

if(sampleVariable == "THIS" || "THAT")

I'm fairly certain the above doesn't work since it will check for the two statements being true separately.

I found this website, which seems to be what I'm looking for. They say that this code is the best way to go around it:

if (fruit.match(/^(banana|lemon|mango|pineapple)$/)) {
    handleYellowFruit();
}

Is this still the way that this is supposed to be done (since the blog post I linked above was published over half a decade ago)? If so, what are these characters in the parentheses: / ^ $ ?

Thanks for the help!

TheKingElessar
  • 1,654
  • 1
  • 10
  • 30
  • 1
    If you only have 2 cases the first example is perfectly perfectly fine and is the best/simplest/most readable way to do it. – Alex K. Apr 09 '18 at 16:08
  • Okay, in my research I couldn't find the duplicate questions - I must have used different terms. Thanks! – TheKingElessar Apr 09 '18 at 16:12

1 Answers1

1

Depending on browser support and ability to polyfill, I'd try array.includes:

if ((["THIS", "THAT"]).includes(sampleVariable)) {
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45