Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 276
amoran Avatar asked Feb 25 '10 17:02

amoran


People also ask

Why is there no logical XOR?

The logical XOR operator is not present in C++ because it is simply an equivalent, not equal to operator with Boolean values.

How do you do XOR operation on bits?

The ^ (bitwise XOR) in C or C++ takes two numbers as operands and does XOR on every bit of two numbers. The result of XOR is 1 if the two bits are different. The << (left shift) in C or C++ takes two numbers, left shifts the bits of the first operand, the second operand decides the number of places to shift.


1 Answers

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;     } 
like image 126
swestrup Avatar answered Oct 06 '22 08:10

swestrup