How does the bitwise XOR (^) operator work?
Ask by Steilla Mitchel
Updated 31 Oct 2023
The bitwise XOR (^) operator in JavaScript is used to perform an exclusive OR operation on the individual bits of two numbers. It returns a number where each bit is set (1) if the corresponding bits of the two numbers being XORed are different, and it sets the bit to 0 if the corresponding bits are the same.
Here's how the bitwise XOR operator works with a simple example:
In this example, the XOR operation is performed on num1 and num2. If the bits at the same positions in both numbers are different, the result has a 1 in that position; otherwise, it has a 0. So, 5 ^ 3 results in 6 because the bits in the binary representation differ at the 2^0 and 2^1 positions.
Remember that the XOR operator can be useful in various scenarios, such as swapping two values without using a temporary variable or toggling specific bits within a number.