Shorter conditional expressions in js

I have the following conditions:

if (foo == 'fgfg' || foo == 'asdf' || foo == 'adsfasdf') {
// do stuff

}

Is there a faster way to write this?

Thank.

+5
source share
7 answers

I would keep conditional expressions as they are. Any smart way to reduce them will make the code less idiomatic and less readable.

Now, if you care about readability, you can define a function to compare:

if( foo_satisfies_condition(foo) ) {
  // ...
}

Or:

if( is_month_name(foo) {
  // ...
}

If you give a function a name that accurately describes what it does, it will be easier to understand the purpose of the code.

How you implement this feature will depend on how many comparisons you need. If you have a really large number of lines with which you are comparing, you can use a hash. However, implementation details do not matter when reading the call code.

+4

switch-case

switch(foo) {
  case "fgfg":
  case "asdf":
  case "adsfasdf":
    // ...
}

, , .

+6
if (/^(fgfg|asdf|adsfasdf)$/.test(foo)) {

if (["fgfg", "asdf", "adsfasdf"].indexOf(foo) != -1) {

- Array.indexOf - . , , , .

+4

indexOf , -:

var things = { 'fgfg' : 1, 'asdf' : 1, 'asdfasdf' : 1 };
if ( things[foo] ) { 
    ... 
}
+4

:

String.prototype.testList = function(lst) {
 lst = lst.split('|');
 for(var i=0; i<lst.length; i++){
  if (this == lst[i]) return true;
 }
 return false;
};

, :

if (foo.testList('fgfg|asdf|adsfasdf')) {

testList | , .

+1

, .

// At some point in your code
var vals = new Array ('fgfg', 'asdf', 'adsfasdf');
// ...
if (vals.indexOf (foo)> = 0)
0
source

The ternary operator looks good if you like, and has more

0
source

All Articles