Why is there no logical xor in JavaScript?
Check out:
You can mimic it something like this:
if( ( foo && !bar ) || ( !foo && bar ) ) {
...
}
JavaScript traces its ancestry back to C, and C does not have a logical XOR operator. Mainly because it's not useful. Bitwise XOR is extremely useful, but in all my years of programming I have never needed a logical XOR.
If you have two boolean variables you can mimic XOR with:
if (a != b)
With two arbitrary variables you could use !
to coerce them to boolean values and then use the same trick:
if (!a != !b)
That's pretty obscure though and would certainly deserve a comment. Indeed, you could even use the bitwise XOR operator at this point, though this would be far too clever for my taste:
if (!a ^ !b)
The reason there is no logical XOR (^^) is because unlike && and || it does not give any lazy-logic advantage. That is the state of both expressions on the right and left have to be evaluated.
Yes, Just do the following. Assuming that you are dealing with booleans A and B, then A XOR B value can be calculated in JavaScript using the following
var xor1 = !(a === b);
The previous line is also equivalent to the following
var xor2 = (!a !== !b);
Personally, I prefer xor1 since I have to type less characters. I believe that xor1 is also faster too. It's just performing two calculations. xor2 is performing three calculations.
Visual Explanation ... Read the table bellow (where 0 stands for false and 1 stands for true) and compare the 3rd and 5th columns.
!(A === B):
| A | B | A XOR B | A === B | !(A === B) |
------------------------------------------
| 0 | 0 | 0 | 1 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 1 | 0 | 1 | 0 | 1 |
| 1 | 1 | 0 | 1 | 0 |
------------------------------------------
Enjoy.
The XOR of two booleans is simply whether they are different, therefore:
Boolean(a) !== Boolean(b)
In Typescript (The + changes to numeric value):
value : number = (+false ^ +true)
So:
value : boolean = (+false ^ +true) == 1