Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorter syntax of conditional or against many Strings

I have something like this:

if(this.selectedItem.label == "str1"
   || this.selectedItem.label == "str2"
   || this.selectedItem.label == "str3"
   || this.selectedItem.label == "str4") {
}

I wonder if exist shorter syntax to use "this.selectedItem.label" only one.

like image 1000
Walter White Avatar asked Aug 16 '17 10:08

Walter White


People also ask

What is the syntax of if condition?

The syntax for if statement is as follows: if (condition) instruction; The condition evaluates to either true or false. True is always a non-zero value, and false is a value that contains zero.

What Is syntax for conditional operator in C?

It is represented by two symbols, i.e., '?' and ':'. As conditional operator works on three operands, so it is also known as the ternary operator. The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.

Is conditional operator faster than if?

Yes! The second is vastly more readable.

How do you shorten an if statement?

Use the ternary operator to use a shorthand for an if else statement. The ternary operator starts with a condition that is followed by a question mark ? , then a value to return if the condition is truthy, a colon : , and a value to return if the condition is falsy.


2 Answers

May be array and indexOf function ?

if(["str1","str2","str3","str4"].indexOf(this.selectedItem.label) > -1){
  // found
}

That's a cross browser solution.

Oh well, includes (haven't tested in IE)

if(["str1","str2","str3","str4"].includes(this.selectedItem.label)){

}
like image 163
Suresh Atta Avatar answered Oct 11 '22 17:10

Suresh Atta


if(["str1", "str2"].indexOf(this.selectedItem.label) !== -1) {
   // TO DO 
}
like image 35
TSV Avatar answered Oct 11 '22 17:10

TSV