Reputation: 455
Sorry for a basic question. How can I simplify the multiple if condition in the following code?:
var x = foo;
if ((x == "val1") || (x == "val2")) {
alert('Hello World');
}
Upvotes: 3
Views: 203
Reputation: 2564
You can't without some clever (or not so clever) programming tricks and you really shouldn't. This code is readable and very simple. You can shorten it, but it will probably stop being readable. You can format it so it looks better though:
var x = foo;
if (x == "val1" || x == "val2") {
alert('Hello World');
}
Also, it is recommended to use ===
instead of ==
in most cases. As to why, read here: Which equals operator (== vs ===) should be used in JavaScript comparisons?
Unless, of course, you have like 20 different values to check. Then making an array and using indexOf
, like suggested in strapro's answer, is probably a decent idea.
Upvotes: 8
Reputation: 61225
You can use regular expressions.
if (/^val[1-2]$/.test(x))
alert("Hello World");
Upvotes: 2
Reputation: 163
Could you please be a little more specific? What do you mean simpler? One way to make it simpler (or more readable actually) would be:
var acceptedValues = ["val1", "val2"];
var x = "foo"
if(acceptedValues.indexOf(x) >= 0){
alert ('Hello World');
}
Upvotes: 2