Is there anyway to implement XOR in javascript

amoran picture amoran · Feb 25, 2010 · Viewed 23.4k times · Source

I'm trying to implement XOR in javascript in the following way:

   // XOR validation
   if ((isEmptyString(firstStr) && !isEmptyString(secondStr)) ||
    (!isEmptyString(firstStr) && isEmptyString(secondStr))
   {
    alert(SOME_VALIDATION_MSG);
    return;
   }

Is there a better way to do this in javascript?

Thanks.

Answer

swestrup picture swestrup · Feb 25, 2010

As others have pointed out, logical XOR is the same as not-equal for booleans, so you can do this:


  // XOR validation
  if( isEmptyString(firstStr) != isEmptyString(secondStr) )
    {
      alert(SOME_VALIDATION_MSG);
      return;
    }