3

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');
}
Tushar
  • 85,780
  • 21
  • 159
  • 179
DDEX
  • 455
  • 3
  • 8
  • 21
  • 6
    `if (['val1', 'val2'].indexOf(x) >= 0)` – fuyushimoya Sep 09 '15 at 07:54
  • 2
    use `switch` instead.. – Guruprasad J Rao Sep 09 '15 at 07:55
  • 1
    I think your code doesn't need further simplifications. – Kaf Sep 09 '15 at 08:01
  • Related question - http://stackoverflow.com/questions/31855433/multiple-conditions-in-an-if-clause/31855768#31855768 – CodingIntrigue Sep 09 '15 at 08:03
  • 1
    I've got to go with @Kaf here, there's nothing the least bit complex about that particular statement. Now, if there were twenty different checks rather than two, I'd give it some thought. But, for what you've specified, best leave it as is. – paxdiablo Sep 09 '15 at 08:03
  • Thanks - that makes sense. Firstly I thought I would do something like: `if (x == "val1"|| "val2") { alert('Hello World'); }` and it didn't work which just surprised me so I thought I was missing some basic syntax rule that would allow it. – DDEX Sep 09 '15 at 08:04

3 Answers3

8

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.

Community
  • 1
  • 1
ralh
  • 2,514
  • 1
  • 13
  • 19
2

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');
}
strapro
  • 153
  • 8
  • Firstly I thought I would do something like: `if (x == "val1"|| "val2") { alert('Hello World'); }` and it didn't work which just surprised me so I thought I was missing some basic syntax rule that would allow it. – DDEX Sep 09 '15 at 07:59
2

You can use regular expressions.

if (/^val[1-2]$/.test(x))
    alert("Hello World");
styvane
  • 59,869
  • 19
  • 150
  • 156
  • @Med I use regex because in OP question they are string not variable – styvane Sep 09 '15 at 08:29
  • Yes but what about if instead of `val1` or `val2` it's 'verylongstring-simplified-toval1' and 'verylongstring-again-simplified-to-val2' ? – Med Sep 09 '15 at 08:36