2

I am using Javascript, and I'd like to make one IF statement that will check one variable against multiple strings using the least amount of code as possible. This is what I used:

if (string == "1" || string == "2" || string == "3" || string == "4") {
console.log("This should execute when string is 1, 2, 3, or 4");
}

How would I go about this same thing with the least amount of code as possible? I am using Javascript.

  • 2
    @NathanHughes While the solutions may be the same, this question isn't a duplicate of that question. – Sean Sep 29 '20 at 16:54
  • @NathanHughes The purpose is to not have duplicate solutions to the same problem persist. This is an entirely different problem—one that future users are likely to encounter—so having a canonical question and solution exist for it is valuable. If this same problem has been posed and solved before, please mark that as duplicate—but not different problems with the same answer. – Sean Sep 29 '20 at 16:59
  • 2
    @NathanHughes Please refer to this post on meta: [Does the same answer imply that the questions should be closed as duplicate?](https://meta.stackoverflow.com/questions/292329/does-the-same-answer-imply-that-the-questions-should-be-closed-as-duplicate) – Sean Sep 29 '20 at 17:06
  • @Sean nice reasoning – hgb123 Sep 29 '20 at 18:05

1 Answers1

4

You could use .includes

if (["1", "2", "3", "4"].includes(string)) {
  console.log("This should execute when string is 1, 2, 3, or 4")
}

hgb123
  • 13,869
  • 3
  • 20
  • 38