1

This is more out of curiosity but is it possible to concatenate comparisons in javascript?

example:

var foo = 'a',
    bar = 'b';
if (foo === ('a' || bar)) {
    console.log('yey');
}

as oposed to...

var foo = 'a',
    bar = 'b';
if (foo === 'a' || foo === bar)) {
    console.log('yey');
}

P.S: When you are comparing the same variable in several conditions, this could be very useful.

Tivie
  • 18,864
  • 5
  • 58
  • 77

4 Answers4

2

You can use Array.indexOf:

if (["a", "b"].indexOf(foo) > -1) {
    console.log("yey");
}

Though this method is not supported by some old browsers, have a look at the compatibility issues in MDN -- there is an easy shim provided.

Another way, suggested by @Pointy in the comments, is to check if property exists in object:

if (foo in {a: 1, b: 1}) {  // or {a: 1, b: 1}[foo]
    console.log("yey");
}
Community
  • 1
  • 1
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

There are several different ways to do this. My favorite is using an array in conjunction with indexOf.

if ( ['a', 'b'].indexOf(foo) > -1 ) {
    console.log('yey');
}
David G
  • 94,763
  • 41
  • 167
  • 253
1

The Array indexOf is one solution

Another option is a switch statement

switch (foo) {
   case "a":
   case "b":
      console.log("bar");
      break;
   case "c":
      console.log("SEE");
      break;
   default:
      console.log("ELSE");
}

other solutions can also be an object look up or a regular expression.

epascarello
  • 204,599
  • 20
  • 195
  • 236
1

Typically I'd use a regex for this:

if (^/a|b$/i.test(foo)) {
  ...
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171