I recently used an xor in a JavaScript project at work and ended up adding 7 lines of comments to explain what was going on. The justification for using xor in that context was that one of the terms (term1
in the example below) could take on not two but three values: undefined
, true
or false
while the other (term2
) could be true
or false
. I would have had to add an additional check for the undefined
cases but with xor, the following was sufficient since the xor forces the first term to be first evaluated as a Boolean, letting undefined
get treated as false
:
if (term1 ^ term2) { ...
It was, in the end, a bit of an overkill, but I wanted to keep it in there anyway, as sort of an easter egg.