Optimize OR in IF

I have a code like this:

if (action == 'John' || action == 'John Beckham' || action == 'Henry John'){
     alert('true!');
}

How do I minimize this code?

Should work in IE7.

Answers:

Answer

If "John" always appears, the simplest thing is:

if (action.toLowerCase().indexOf("john") !== -1) {
    // Do something
}

...but as your question has already changed the values against which you're checking action once, I hesitate to assume that. Also note that it will match "xxxjohnxxx", which may not be what you want.

Original suggestions (updated for new action values from your edit):


There are lots of ways, all shown using case insensitivity since you mentioned that in the comments:

String#indexOf:

if ("|john|john beckham|john henry|giggs john|scholes john|john messi|".indexOf("|" + action.toLowerCase() + "|") !== -1) {
    // Do something
}

Regular expressions:

if (/^(?:John|John Beckham|John Henry|Giggs John|Scholes John|John Messi)$/i.test(action)) {
    // Do something
}

Because you're just using the true/false result, I'm using test which just returns true/false, instead of exec which returns matching results. Both work in this case, but the browser may be able to ever-so-slightly optimize test (but then, regex is unlikely to be the best solution if your goal is the fastest result or the least memory use).


Or a switch:

switch (action.toLowerCase()) {
    case "john":
    case "john beckham":
    case "john henry":
    case "giggs john":
    case "scholes john":
    case "john messi":
        // Do something
}

Or an object lookup:

var actions = {
    "john":         true,
    "john beckham": true,
    "john henry":   true,
    "giggs john":   true,
    "scholes john": true,
    "john messi":   true
};

if (actions[action.toLowerCase()]) {
    // do something
}

(That also has the advantage of letting you say what to do — e.g., the true could be replaced with a function you call.)


Or (on an ES5-enabled environment or with an ES5 shim) Array#indexOf:

if (["john", "john beckham", "john henry", "giggs john", "scholes john", "john messi"].indexOf(action.toLowerCase()) !== -1 {
    // Do something
}

or since you use jQuery, you can avoid the shim on older browsers by using inArray:

if ($.inArray(action.toLowerCase(), ["john", "john beckham", "john henry", "giggs john", "scholes john", "john messi"]) !== -1) {
    // Do something
}
Answer

if using jquery, then you could do:

var arr = ['a','b','c','d','e','f','g'];
if( $.inArray(action, arr) !== -1 ) {
  alert("true");
}
Answer

Try this, it uses indexOf:

if (['a', 'b', 'c', 'd', 'e'].indexOf(action) > -1) {
  alert(true);
}

Update: If you want to support IE7 and below, use the answer to this question

If you're using jQuery, you can use $.inArray like this:

if ($.inArray(action, ['a','b','c','d') > -1) {
  alert(true);
}

UPDATE

You can also use a regexp with test (The group makes the regexp not match "John Langhammerer" / actions with extra chars to the ones to be matched):

if ((/^(John Langhammer|Piet Krauthammer|Some Guy)$/i).test(action)) {
  alert(true);
}

UPDATE: /i makes the regexp case insensitive.

Below is a solution which would have worked for one-char actions:

You can also use String.indexOf which is supported in IE7 (if your actions are all one char):

if ('abcde'.indexOf(action) > -1) {
  alert(true);
}
Answer

Make an array as below.

var newAry = array('a','b','c');

Now just check it as below.

$(function()
{
    var newAry = Array('a','b','c');
    if($.inArray(action,newAry)){ alert(action); }
});
Answer

Cross-browser solution:

if ( action in {'John':1, 'John Beckham':1, 'John Henry':1, 'Giggs John':1, 'Scholes John':1, 'John Messi':1 } ){
     alert('true!');
}
Answer

In addition of indexOf, you can also use conditional operator in Javascript.

names = ['John' , 
         'John Beckham', 
         'John Henry' , 
         'Giggs John' , 
         'Scholes John', 
         'John Messi'
];
names.indexOf(action) != -1? alert('True') : alert ('False');

And you want to do more then simple statement do like:

 names.indexOf(action) != -1? doSomethingOnTrue() : doSomethingOnFalse(); 
Answer
if('abcdefg'.indexOf(action) > -1){
    // action is one of 'abcdef'
}

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.