XOR in JavaScript
Typically when writing a XOR check in JavaScript you would do something like…
if (( foo || bar ) && !( foo && bar )) { }
The issue with this approach is that it can be very verbose when not in psudo code or you will have to convert each expression into a boolean value prior to the check to get it as small as the above example.
In order to start working towards a better solution we first need to define our desired outcome. Wikipedia explains an exclusive or (XOR) to be a logical operation that outputs true whenever both inputs differ (one is true, the other is false).
Input A | Input B | Output |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
So with the truth table above we can now check out alternative approaches. As it turns out the quirkyness of JavaScript can actually help us clean this up. Because using the NOT (!) operator on a string will typecast it to false we can actually reduce the above if check to…
if (!foo != !bar) { }
So lets create an output table for this new technique to see if it works as expected.
Input A | Input B | Output |
---|---|---|
0 | 0 | false |
0 | 1 | true |
1 | 0 | true |
1 | 1 | false |
Works great and with a lot less keystrokes!
Thanks for reading! If you have any questions or comments please feel free to comment below or mention me on twitter @fromanegg.