Question

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!

Was it helpful?

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)

OTHER TIPS

Let me illustrate with an example:

2 ^ 1 = 3
In binary
10 ^ 01 = 11

At a bitwise level, A^B = 1 if A != B

shouldBeCollapsed looks like a boolean variable in which case you are doing it wrong. What you are looking for is :

if (shouldBeCollapsed) { 
    // Code to collapse
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top