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.

2
  • Oops. It's a dupe allright. I actually searched here but couldn't find anything. Commented Jan 24, 2013 at 23:56
  • edited so it becomes a little different Commented Jan 25, 2013 at 0:05

4 Answers 4

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

Seems like if ({a: 1, b: 1}[foo])) would be a little nicer.
@Pointy ... or foo in {a: 1, b: 1}.
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');
}

1 Comment

Very interesting. Haven't thought of using indexOf.
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.

3 Comments

Yes. Although this wouldn't work if right side isn't a string or a number.
@Tivie give an example of what would fail? switch is not limited to strings and numbers.
I'm sorry you're right. Seems javascript lets you switch/case with variables
1

Typically I'd use a regex for this:

if (^/a|b$/i.test(foo)) {
  ...
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.