Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is Bitwise XOR Assignment Operator (^=) in JavaScript?
The Bitwise XOR Assignment Operator (^=) performs an XOR (exclusive OR) operation between the left and right operands, then assigns the result back to the left operand. It's a shorthand for a = a ^ b.
Syntax
variable ^= value; // Equivalent to: variable = variable ^ value;
How XOR Works
XOR returns 1 when bits are different, 0 when they're the same:
let a = 2; // Binary: 10
let b = 3; // Binary: 11
console.log("Before: a =", a, "b =", b);
a ^= b; // XOR and assign
console.log("After a ^= b:", a);
Before: a = 2 b = 3 After a ^= b: 1
Step-by-Step Explanation
Let's see how the XOR operation works bit by bit:
let x = 5; // Binary: 101
let y = 3; // Binary: 011
console.log("x =", x, "binary:", x.toString(2));
console.log("y =", y, "binary:", y.toString(2));
x ^= y; // 101 XOR 011 = 110
console.log("x ^= y result:", x, "binary:", x.toString(2));
x = 5 binary: 101 y = 3 binary: 11 x ^= y result: 6 binary: 110
Common Use Cases
XOR assignment is useful for toggling bits and swapping variables:
// Toggling a bit flag
let flags = 5; // Binary: 101
let toggle = 4; // Binary: 100
console.log("Original flags:", flags.toString(2));
flags ^= toggle;
console.log("After toggle:", flags.toString(2));
// Swap two numbers without temporary variable
let num1 = 10;
let num2 = 20;
console.log("Before swap: num1 =", num1, "num2 =", num2);
num1 ^= num2;
num2 ^= num1;
num1 ^= num2;
console.log("After swap: num1 =", num1, "num2 =", num2);
Original flags: 101 After toggle: 1 Before swap: num1 = 10 num2 = 20 After swap: num1 = 20 num2 = 10
Conclusion
The XOR assignment operator (^=) is a concise way to perform bitwise XOR operations. It's particularly useful for bit manipulation, toggling flags, and creative algorithms like variable swapping.
Advertisements
