Search code examples
javascriptvalidationxor

Is there anyway to implement XOR in javascript


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.


Solution

  • I pretend that you are looking for a logical XOR, as javascript already has a bitwise one (^) :)

    I usually use a simple ternary operator (one of the rare times I use one):

    if ((isEmptyString(firstStr) ? !isEmptyString(secondStr) 
                                 : isEmptyString(secondStr))) {
    alert(SOME_VALIDATION_MSG);
        return;
    }
    

    Edit:

    working on the @Jeff Meatball Yang solution

    if ((!isEmptyString(firstStr) ^ !isEmptyString(secondStr))) {
      alert(SOME_VALIDATION_MSG);
      return;
    }
    

    you negate the values in order to transform them in booleans and then apply the bitwise xor operator. Maybe it is not so maintainable as the first solution (or maybe I'm too accustomed to the first one)