mattsven
mattsven

Reputation: 23303

Shorthand IF Statement

I'm curious, is there a simpler way to say

if(myVar == myVal || myVar == myOtherVal){ /*...*/ }

such as:

if(myVar == myVal || myOtherVal){ /* */ }

I am aware that my proposed code only checkes to see whether myVar equals myVal or myOtherVal is not null (undefined) and false.

So, as I stated before, is there a simpler way to write

if(myVar == myVal || myVar == myOtherVal){ /*...*/ }

Just curious to know if there's some sort of jS shorthand if statment that works like this that I have missed.

Thanks in advance.

Upvotes: 0

Views: 1203

Answers (5)

Pete
Pete

Reputation: 10871

Ternary Operator:

result = ((myVar==myval)||(myVar==myOtherVal)) ? x : y;

Can be:

if((myVar==myVal) || (myVar==myOtherVal))
   result = x;
else
   result = y;

Also:

((myVar==myval)||(myVar==myOtherVal)) ? someFunction() : otherFunction();

Is the same as:

if((myVar==myVal) || (myVar==myOtherVal))
    someFunction();
else
    otherFunction();

Upvotes: 0

RobG
RobG

Reputation: 147553

Another way is to use && as a "guard":

(myVar == myVal || myVar == myOtherVal) && /* expression */

But I don't recommend it. Your code should be easily read and maintained, so:

if (myVar == myVal || myVar == myOtherVal) {
  /* do stuff */
}

is much better to me.

Upvotes: 0

Sufendy
Sufendy

Reputation: 1242

This should be what you are looking for. http://snook.ca/archives/javascript/testing_for_a_v

Upvotes: 1

alex
alex

Reputation: 490657

Not that I know of.

You could use the Array's indexOf with an array if you really wanted.

Upvotes: 0

Ry-
Ry-

Reputation: 225281

You could use arrays:

if([myVal, myOtherVal].indexOf(myVar) + 1) { /* or > -1 or !== -1 */ }

Or switch statements:

switch(myVar) {
     case myVal:
     case myOtherVal:
          /* */
          break;
}

These only really apply when comparing the variable to more than two possible values, though.

Upvotes: 1

Related Questions