0

I often write this repetitive code:

if (SERVER_ENV == "TEST" || SERVER_ENV == "PROD" || SERVER_ENV == "QA") {
  // ...
}

Is there a better way to write conditional checks like this in Javascript? When you need to check against more than one pre-defined value.

I mean, I could do:

const POSSIBLE_ENVS = ["TEST","PROD","QA"];

if (POSSIBLE_ENVS.includes(SERVER_ENV))

// OR

if (POSSIBLE_ENVS.indexOf(SERVER_ENV) >= 0)

But that is cumbersome and it inverts my logical thinking. I'm writing does that array contain my value ? instead of is my value inside that array ?

How to people usually handle this? Is there a ECMA proposal or any other syntactical sugar available?

cbdeveloper
  • 27,898
  • 37
  • 155
  • 336
  • Side-note: you probably should be using `===` instead of `==`. – Dai Jan 18 '21 at 11:48
  • Well, a `switch` statement, but that's not a succinct expression. – Dai Jan 18 '21 at 11:49
  • 1
    Use `includes`. Deal with it. JavaScript isn't going to be pretty all the time, sausage has to get made. – tadman Jan 18 '21 at 11:49
  • 1
    Thank you all. Will delete this question. – cbdeveloper Jan 18 '21 at 11:50
  • You could also define a new function property on `String.prototype.oneOf = ( values... ) => values.includes( this );` and used like `if( SERVER_ENV.oneOf( "TEST", "PROD", "QA" ) ) { ...` – Dai Jan 18 '21 at 11:50
  • If you're doing a lot of tests use [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). – tadman Jan 18 '21 at 11:50

0 Answers0