Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there JS shorthand for conditional "not equal to a and not equal to b" and such?

I was just wondering if there is some JS shorthand for something like this:

if (x != 1 && x != 2) do stuff;

Does such a beast exist? Instead, I want to say something like this:

if (x != 1:2) do stuff;

like image 633
Slink Avatar asked Dec 14 '12 02:12

Slink


1 Answers

No, there is no such shorthand.

You can use a switch if you don't want to repeat the variable:

switch (x) {
  case 1:
  case 2: break;
  default: do stuff;
}

Another alternative would be to look for the value in an array:

if ([1, 2].indexOf(x) == -1) do stuff;

However, the Array.indexOf doesn't exist in all browsers, so you may need a fallback which you can for example find on the Mozilla Array.indexOf documentation page.

like image 188
Guffa Avatar answered Sep 18 '22 00:09

Guffa