0

Is there a shorter way to manage a list of matching values for the same variable in a Typescript IF statement?

if(X==5 || X==undefined || X=="") {
     //do something...
}

1 Answer 1

2

Syntactically, you can use switch instead of if to test for multiple values using repeating cases:

switch (x) {
  case 5:
  case "":
  case undefined:
    // do something
    break;
}

But this is rarely done.

To programatically test for multiple values, you can put the values in an array and check that it includes your argument value using indexOf:

if ([5, "", undefined].indexOf(x) >= 0) {
  ...
}

Note that this will create the values array each time, so if this check repeats you might want to create the array once, elsewhere, and reuse it.

const values = [5, "", undefined];

// elsewhere
if (values.indexOf(x) >= 0) {
  ...
}

In fact, if the number of values to test is large, you might want to put them in a Set and check that it has them, as this is faster than testing against an array:

const values = new Set(5, "", undefined);

// elsewhere
if (values.has(x)) {
  ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.