Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of ^= operator in JS [duplicate]

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.

like image 437
shannoga Avatar asked Apr 07 '13 13:04

shannoga


People also ask

What is the meaning of === operator?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result.

What does ~~ mean in JS?

The Complete Full-Stack JavaScript Course! The “double tilde” (~~) operator is a double NOT Bitwise operator. Use it as a substitute for Math. floor(), since it's faster.

What does == === mean?

The === operator means "is exactly equal to," matching by both value and data type. The == operator means "is equal to," matching by value only.

What is different between == and === in JS?

The main difference between the == and === operator in javascript is that the == operator does the type conversion of the operands before comparison, whereas the === operator compares the values as well as the data types of the operands.


2 Answers

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
like image 166
Thalaivar Avatar answered Nov 06 '22 00:11

Thalaivar


^ (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.

like image 21
ASGM Avatar answered Nov 06 '22 00:11

ASGM