0

I am trying to make an if statement in javascript that will do something if the variable does not equal one of a few different things. I have been trying many different variations of the OR operator, but I cant get it to work.

 if(var != "One" || "Two" || "Three"){
    // Do Something
    }

Any ideas? Thanks!

Update:

I have tried this before:

 if(var != "One" || var != "Two" || var != "Three"){
    // Do Something
    }

For some reason it does not work. My variable is pulling information from the DOM i dont know if that would effect this.

Actual Code

// Gets Value of the Field (Drop Down box)
var itemtype = document.forms[0].elements['itemtype' + i];

    if(itemtype.value != "Silverware" || itemtype.value != "Gold Coins" || itemtype.value != "Silver Coins"){   
// Do Something
        }
1
  • 5
    as a side note: var is a keyword, not a variable name Commented Jan 6, 2010 at 6:07

6 Answers 6

8

Your expression is always true, you need:

if(!(myVar == "One" || myVar == "Two" || myVar == "Three")) { 
  // myVar is not One, Two or Three
} 

Or:

if ((myVar != "One") && (myVar != "Two") && (myVar != "Three")) {
  // myVar is not One, Two or Three
}

And, for shortness:

if (!/One|Two|Three/.test(myVar)) {
  // myVar is not One, Two or Three
}
// Or:
if (!myVar.match("One|Two|Three")) {
  // ...
}

More info:

Edit: If you go for the last approaches, since the code you posted seems to be part of a loop, I would recommend you to create the regular expression outside the loop, and use the RegExp.prototype.test method rather than String.prototype.match, also you might want to care about word boundaries, i.e. "noOne" will match "One" without them...

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you, finally a sensible answer. I will try it now.
I would use the regexp !myVar.match(/One|Two|Three/) instead of passing in the string - but +1 for covering all the bases
@Chris... he has 56K for a reason :) @CMS +1, great answer as always
@gnarf, Agree, and the RegExp should be created outside the loop (the code fragment appears to be part of a loop (...['itemtype' + i];...))
Wait, doesn't the OP want to do something only if the value is not "One" or "Two" or "Three"? If so, the expression !/One|Two|Three/.test(myVar) is not correct. The value "Ones" is not "One" but it is matched by /One/. You want to use ^ and $.
6

Assuming you mean "val does not equal One or Two or Three" then De Morgan's Theorem applies:

if ((val != "One") && (val != "Two") && (val != "Three")) {
  // Do something...
}

1 Comment

Equivalently, !(var == "One" || var == "Two" || var == "Three").
0

For a shorter way to do it, try this format (copied from http://snook.ca/archives/javascript/testing_for_a_v):

if(name in {'bobby':'', 'sue':'','smith':''}) { ... }

or

function oc(a)
{
  var o = {};
  for(var i=0;i<a.length;i++)
  {
    o[a[i]]='';
  }
  return o;
}
if( name in oc(['bobby', 'sue','smith']) ) { ... }

5 Comments

the second two methods are good, the first is wrong as discussed on other answers (|| should be &&).
Thanks cobbal, I'll fix my answer.
I tried this before but it was lacking because I need the opposite. not in.
No cobbal, not && it needs to be ||
not (a or b) is equivalent to (not a) and (not b) en.wikipedia.org/wiki/De_Morgan's_laws
0

The method mentioned by Mike will work fine for just 3 values, but if you want to extend it to n values, your if blocks will rapidly get ugly. Firefox 1.5+ and IE 8 have an Array.indexOf method you can use like so:

if(["One","Two","Test"].indexOf(myVar)!=-1)
{
    //do stuff
}

To support this method on IE<=7, you could define a method called Array.hasElement() like so:

Array.prototype.hasElement = function hasElement(someElement)
{
    for(var i=0;i<this.length;i++)
    {
        if(this[i]==someElement) 
            return true;
    }
    return false;
}

And then call it like so:

if(!["One","Two","Three"].hasElement(myVar))
{
    //do stuff
}

Note: only tested in Firefox, where this works perfectly.

Comments

-1

In addition to expanding the expression into three clauses, I think you'd better name your variable something other than var. In JavaScript, var is a keyword. Most browsers aren't going to alert you to this error.

2 Comments

the variable isnt really var. it was an example only.
+1 for pointing out the issue with var identifier. I don't know why this is down voted.
-1

Alternate way using an array:

var selected = ['Silverware', 'Gold Coins', 'Silver Coins'];
if ( selected.indexOf( el.value ) != -1 ) {
   // do something if it *was* found in the array of strings.
}

Note: indexOf isnt a native method, grab the snippet here for IE:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.