Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the operator "^"? [duplicate]

Possible Duplicate:
What does the ^ operator do?

>>> var foo = [1,2]
>>> var bar = [3,4]
>>> foo ^ bar
0
>>> foo ^ 3
3
>>> 1^3
2

What is the purpose of the operator: ^?

Edit 1: Can you explain why

>>> foo ^ bar
0

?

like image 794
JohnJohnGa Avatar asked Dec 27 '22 12:12

JohnJohnGa


1 Answers

In the case of 1^3, the XOR operator does some binary stuff to get 2.

    1 = 00000001 ^
    3 = 00000011
        ========
        00000010 = 2

JavaScript sees the array syntax [x,y] as NaN when you start doing math-y things with it. NaN is interpreted as 0 when you do bitwise operations on it, so the foo and bar math starts to make sense taking that into account:

foo => NaN = 00000000 ^
bar => NaN = 00000000
             ========
             00000000 = 0

foo => NaN = 00000000 ^
         3 = 00000011
             ========
             00000011 = 3

Which seems to hold true. [1,2]^7 = 7, [1,2,3]^9 = 9, etc.

like image 119
Cᴏʀʏ Avatar answered Dec 30 '22 11:12

Cᴏʀʏ