Logical XOR in Javascript

XOR (exclusive OR) is a boolean operation, like && and ||, but with the following logic: It is true if the expression on either side is true (like ||), but not if both sides are true (like &&).

Sometimes, in your JavaScript, you might want to do the following:

if( foo XOR bar ) { ... }

Unfortunately, JavaScript does not have a logical XOR operator. This article covers several methods of performing an XOR manually, and concludes with a surprisingly succinct way of doing it, summarized below.

The cleanest and best

The XOR operation can be described as “return true if the two boolean operands do not have the same value”. So the actual response that is wanted is just this:

if( foo != bar ) { ... }

That works if the two operands are both boolean true/false. However, to allow for other variable types (strings, expressions, etc.), it cannot work, since ‘string’ does not equal /regex/, even though the XOR operation would be expected to return false. So the operands need to be converted into boolean values first. This can be done like this:

foo ? true : false

However, it is easier and quicker to simply use the ! operator. This will give the opposite value – false instead of true, but as long as both operands get the same treatment, this will not affect the end result. So the simplest, cleanest version of the XOR operator, that works with any data types, including expressions, is this:

if( !foo != !bar ) { ... }

3 thoughts on “Logical XOR in Javascript”

  1. Even slightly shorter is

    if(!foo^!bar){…}

    I’ve tested it works great ands runs slightly faster!

  2. @Jonathan
    Thanks for this useful info. I’ll give the various XOR workarounds a shot.

    @Joe
    Yes and it looks slightly more confusing too. In my opinion spacing counts. But to each his own I guess.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>