Search code examples
javascriptbit-manipulationxor

Javascript XOR operation (trying to understand!)


I've been researching the caret (XOR) operator in Javascript, but i'm having a heck of a hard time understanding.

Can someone explain why, for example, 1 ^ 1 = 0?

I have some code someone wrote, and they are doing the following:

if (shouldBeCollapsed ^ 1)
{
   //code to collapse section of page.
}

But if the shouldBeCollapsed variable is equal to 1, the condition fails. I'm just trying to understand the logic behind the ^ operator, and it's kind of confusing me!

Thanks!


Solution

  • That is the definition of XOR. X ^ Y is 1 iff X != Y. Thus, if X and Y are both 1, then XOR is 0.

    The truth table is as follows:

    X  Y  X^Y
    0  0   0
    0  1   1
    1  0   1
    1  1   0
    

    X ^ Y is logically equivalent to (X && !Y) || (!X && Y)