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.
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.
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.
Yes! The second is vastly more readable.
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.
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)){
}
if(["str1", "str2"].indexOf(this.selectedItem.label) !== -1) {
// TO DO
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With