JavaScript Tutorial JavaScript References

JavaScript - Bitwise XOR and assignment operator



The Bitwise XOR and assignment operator (^=) assigns the first operand a value equal to the result of Bitwise XOR operation of two operands.

(x ^= y) is equivalent to (x = x ^ y)

The Bitwise XOR operator (^) is a binary operator which takes two bit patterns of equal length and performs the logical exclusive OR operation on each pair of corresponding bits. It returns 1 if only one of the bits is 1, else returns 0.

Bit_1Bit_2Bit_1 ^ Bit_2
000
101
011
110

The example below describes how bitwise XOR operator works:

50 ^ 25 returns 43

     50    ->    110010  (In Binary)
   ^ 25    ->  ^ 011001  (In Binary)
    ----        --------
     43    <-    101011  (In Binary)  

The code of using Bitwise XOR and assignment operator (^=) is given below:

var x = 50;
var y = 25;
var txt;

//Bitwise XOR and assignment operation
x ^= y;
txt = "x = " + x;

The output (value of txt) after running above script will be:

x = 43

Example: Swap two numbers without using temporary variable

The bitwise XOR and assignment operator can be used to swap the value of two variables. Consider the example below.

var x = 10;
var y = 25;
var txt;

txt = "Before Swap: <br>";
txt = txt + "x = " + x + ", y = " + y + "<br><br>";

//Swap technique
x ^= y;
y ^= x;
x ^= y;

txt = txt + "After Swap: <br>";
txt = txt + "x = " + x + ", y = " + y + "<br>";

The output (value of txt) after running above script will be:

Before Swap:
x = 10, y = 25

After Swap:
x = 25, y = 10

❮ JavaScript - Operators