5

I am trying to figure out this operator on JS -

'string' ^= 'string';

But I can not find ant information. Is that a comparison or assignment ?

Thanks.

shannoga
  • 19,000
  • 20
  • 99
  • 163

4 Answers4

7

myVar ^= 5 is the same as myVar = myVar ^ 5. ^ is the bitwise xor operator

Let's say myVar was set to 2

  • 5 in binary is: 101
  • 2 in binary is: 010

Exclusive "or" checks the first bit of both numbers and sees 1,0 and returns 1 then sees 0,1 and returns 1 and sees 1,0 and returns 1.

Thus 111 which converted back to decimal is 7

So 5^2 is 7

var myVar = 2;
myVar ^= 5;
alert(myVar); // 7
0x499602D2
  • 87,005
  • 36
  • 149
  • 233
Thalaivar
  • 20,946
  • 5
  • 57
  • 67
  • You might consider editing the `5^2 is 7` part. I thought for a moment you meant '5 to the power of 2', which is, of course, 25 and not 7. – 11684 Apr 07 '13 at 13:21
  • @11684: Math.pow does that in JavaScript. Nothing to be confused about here. alert(5^2);//7 – Thalaivar Apr 07 '13 at 13:24
  • 1
    I know, but it still was confusing. I +1'ed after you wrapped it in `s though. – 11684 Apr 07 '13 at 13:30
4

^ (caret) is the Bitwise XOR (Exclusive Or) operator. As with more common operator combinations like +=, a ^= b is equivalent to a = a^b.

See the Javascript documentation from Mozilla for more details.

ASGM
  • 9,243
  • 25
  • 46
2

x ^= y is bitwise XOR and shorthand for x = x^y - and so is technically an "assignment" to answer your question. And to be precise the single operator '^' indicates the bitwise XOR.

d'alar'cop
  • 2,342
  • 1
  • 12
  • 17
1

As d'alar'cop (and several others by now) already pointed out, this means something called XOR. I always hate to read a wikipedia explanation, so I'm going to put another explanation here:

'XOR' means 'eXclusive OR'. What is that? First an example:

11000110 -- random byte
10010100
--------- ^ -- XOR
01010010

XOR is some bitwise operation, returning two if one of two bits is 1 and the other 0. If they're both 1, it's 'and', not 'exclusive or' ('normal or' would allow two 1's).

11684
  • 7,120
  • 10
  • 45
  • 69