JavaScript Bitwise Operators
Bitwise operators work on the binary (0s and 1s) representation of numbers. They are used less often than arithmetic or logical operators but are useful for low-level programming, performance tricks, or handling flags.
1. AND (&)
Performs an AND operation on each bit.
let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
console.log(a & b); // 1 (0001 in binary)
2. OR (|)
Performs an OR operation on each bit.
let a = 5; // 0101
let b = 3; // 0011
console.log(a | b); // 7 (0111)
3. XOR (^)
Performs an exclusive OR operation (true if bits are different).
let a = 5; // 0101
let b = 3; // 0011
console.log(a ^ b); // 6 (0110)
4. NOT (~)
Flips all bits (0 → 1, 1 → 0).
let a = 5; // 0101
console.log(~a); // -6 (two’s complement)
5. Left Shift (<<)
Shifts bits to the left, adding 0s on the right.
let a = 5; // 0101
console.log(a << 1); // 10 (1010)
6. Right Shift (>>)
Shifts bits to the right, keeping the sign.
let a = 5; // 0101
console.log(a >> 1); // 2 (0010)
7. Zero-fill Right Shift (>>>)
Shifts bits to the right and fills with 0s, ignoring the sign.
let a = -5;
console.log(a >>> 1); // 2147483645
Operator | Meaning | Example |
---|---|---|
& | AND | 5 & 3 (0101 & 0011 = 0001 → 1) |
` | ` | OR |
^ | XOR | 5 ^ 3 (0101 ^ 0011 = 0110 → 6) |
~ | NOT | ~5 (0101 → 1010 → -6) |
<< | Left Shift | 5 << 1 (0101 → 1010 → 10) |
>> | Right Shift | 5 >> 1 (0101 → 0010 → 2) |
>>> | Zero-fill Right Shift | 5 >>> 1 (0101 → 0010 → 2) |