Why is there no logical xor in JavaScript?

DarkLightA picture DarkLightA · Dec 27, 2010 · Viewed 83.6k times · Source

Why is there no logical xor in JavaScript?

Answer

John Kugelman picture John Kugelman · Dec 27, 2010

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)