views:

147

answers:

6

Can I make this statement shorter?

if(abc=='value1' || abc=='value2' || abc=='value3') {//do something}

to make it look similar to this:

if(abc=='value1' || 'value2' || 'value3'){//do something}

Thanks.

+9  A: 

You have a couple options:

  1. Leave it as it is;
  2. Use an associative array/object;
  3. Use a switch statement.

The second form is not valid Javascript syntax.

(2) is something like:

var abcOptions = {
  "value1" : true,
  "value2" : true,
  "value3" : true
};
if (abcOptions[abc]) {
  ...
}

(3) is:

switch (abc) {
  case "value1":
    ...
    break;
  case "value2":
    ...
    break;
  case "value3":
    ...
    break;
}

Personally I'm not a huge fan of this from a readability point of view but it's a reasonable approach with a large number of values.

I don't necessarily recommend this but it might be an option in certain circumstances. If you're only dealing with three values stick with:

if (abc == "value1" || abc == "value2" || abc == "value3") {
  ...
}

as it's much more readable.

cletus
Try the second option with for example abc='toString'...
Guffa
A: 
if ( abc.search(/value[123]/) != -1 ) ...do your stuff ...
aefxx
`xxxvalue1xxx` will return 0 as well
o.k.w
So would myvalue2blahblah. What's the point? I think he could figure out to do /^value[123]$/ if that were a problem.
aefxx
A: 

You could use a switch statement. Like this:

switch(abc) {
    'value1':
    'value2':
    'value3':
         // do something
         break;
    default:
         // noop
}

But your original if with || is probably still preferable.

Asaph
+1  A: 

You can use a switch:

switch (abc) { case 'value1': case 'value2': case 'value3': {
  // do something
}}

Or written in a more traditional form:

switch (abc) {
  case 'value1':
  case 'value2':
  case 'value3': {
    // do something
  }
}
Guffa
Upvote for using the fall-through case syntax. It isn't any shorter than the OP's code, though :)
Merlyn Morgan-Graham
+1  A: 
if(abc.match(/^value[1-3]$/)) {
    //doSomething....
}
o.k.w
My comment on the OP's question still stands. Readability has to count for something. This is not nearly as readable. Getting all "fancy" is not necessary if you're sacrificing readability.
rockinthesixstring
I am all for code readability, just that this specific regex aren't that fancy (and imho, rather readable). But considering the values are arbiturary, I suppose you are right. :)
o.k.w
Seems the best solution to making the statement shorter. Or similarly:/^(value1|value2|value3)$/.test(abc)
Sean Hogan
+1  A: 
if (['value1', 'value2', 'value3'].indexOf(abc) != -1)

This one manages to remain somewhat readable, but you should leave your original code as-is unless you have way more conditions.

Wallacoloo
Or potentially:if ("value1 value2 value3".split(" ").indexOf(abc) != -1)or make it a reusable function:function hasToken(text, token) { return text.split(" ").indexOf(token) != -1; }
Sean Hogan