The JavaScript XOR operator is the bitwise exclusive OR operator written as ^. It compares the binary form of two numbers and returns a value where matching bits become 0 and different bits become 1.
XOR is useful for bit toggling, bit masks, and numeric operations that depend on binary comparison. It is part of the broader set of JavaScript operators that also includes logical and bitwise forms.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Method 1: Use XOR with two numbers
The operator compares each bit in the two values and returns a new number.
console.log("xor:", 25 ^ 3);
console.log("xor-even:", 5 ^ 5);You should see 2 lines, in order: xor: 26, xor-even: 0.
This makes XOR useful when you need to inspect or transform bits directly.
Method 2: Toggle a bit with XOR
Applying ^ with the same mask twice flips a bit on and then off again.
let byte = 0b11110000;
byte ^= 0b00000100;
console.log("xor-toggle:", byte.toString(2));
byte ^= 0b00000100;
console.log("xor-toggle-back:", byte.toString(2));You should see 2 lines, in order: xor-toggle: 11110100, xor-toggle-back: 11110000.
This is the common pattern for setting or clearing a specific bit.
Method 3: Use XOR for small binary checks
XOR is helpful when you want to compare two flags or verify whether two bits differ.
const a = 12;
const b = 10;
const result = a ^ b;
console.log("xor-check:", result);You should see one line logging xor-check: 6.
For ordinary text comparisons or boolean logic, use a logical operator instead of the bitwise one.
Summary
JavaScript XOR is the bitwise exclusive OR operator and is written with ^. Use it when you need binary comparison, toggling, or low-level numeric work, and remember that it operates on 32-bit integer values after conversion.
