JavaScript - Bitwise Operations Part 3: Bitwise OR (|) and XOR (^)
How OR (|) Works
The OR operator returns 1 if at least one bit is 1.
Example 3: OR Operation
console.log(5 | 3); // Output: 7
Binary representation:
5 = 101
3 = 011
------------
Result = 111 (7 in decimal)
At least one bit is 1, so the result is 7.
How XOR (^) Works
The XOR (Exclusive OR) operator returns 1 only if the bits are different.
Example 4: XOR Operation
console.log(5 ^ 3); // Output: 6
Binary representation:
5 = 101
3 = 011
------------
Result = 110 (6 in decimal)
Only the middle two bits are different, so the result is 6.
Use Case: Swapping Two Numbers Without a Temporary Variable
let a = 5, b = 3;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a, b); // Output: 3, 5
Explanation:
XOR helps swap values without needing extra space.