Bitwise Operators in JavaScript
Bitwise operators perform operations on the binary (base-2) representations of numbers. They
work on 32-bit integers (numbers are converted to 32-bit signed integers during operations).
---
1. Bitwise AND (`&`)
Returns `1` only if both corresponding bits are `1`.
Truth Table
|A|B|A&B|
|---|---|-------|
|0|0| 0 |
|0|1| 0 |
|1|0| 0 |
|1|1| 1 |
Example
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let c = a & b; // Result: 0001 (1 in decimal)
console.log(c); // 1
# Use Case
- Checking if a number is odd/even :
if (num & 1) {
console.log("Odd"); // Last bit is 1
} else {
console.log("Even"); // Last bit is 0
---
2. Bitwise OR (`|`)
Returns `1` if at least one corresponding bit is `1`.
# Truth Table
|A|B|A|B|
|---|---|-----|
|0|0| 0|
|0|1| 1|
|1|0| 1|
|1|1| 1|
# Example
let a = 5; // 0101
let b = 3; // 0011
let c = a | b; // 0111 (7 in decimal)
console.log(c); // 7
---
3. Bitwise NOT (`~`)
Flips all bits (`0` → `1`, `1` → `0`).
- Equivalent to `-(x + 1)` (due to two's complement representation).
# Example
let a = 5; // Binary: 0000 0000 0000 0101
let b = ~a; // Binary: 1111 1111 1111 1010 (-6 in decimal)
console.log(b); // -6
---
4. Left Shift (`<<`)
Shifts bits to the left and fills with `0`.
- Equivalent to multiplying by `2ⁿ` (where `n` = shift amount).
# Example
let a = 5; // 0000 0101
let b = a << 2; // 0001 0100 (20 in decimal)
console.log(b); // 20 (5 * 2² = 20)
Right Shift (`>>`)
Shifts bits to the right (preserves the sign bit).
- Equivalent to dividing by `2ⁿ` (floor division).
# Example
let a = 16; // 0001 0000
let b = a >> 2; // 0000 0100 (4 in decimal)
let c = -16 >> 2; // -4 (sign bit is preserved)
---
6. Zero-Fill Right Shift (`>>>`)
Shifts bits to the right and fills with `0` (ignores sign bit).
- Always returns a positive number .
# Example
let a = -16; // 1111 1111 1111 0000
let b = a >>> 2; // 0011 1111 1111 1100 (1073741820 in decimal)
console.log(b); // 1073741820
# Use Case
- Extracting unsigned values (e.g., color manipulation).
---
Summary Table
| Operator | Name | Example | Result (`a=5`, `b=3`) |
|----------|------|---------|-----------------------|
| `&` | AND | `a & b` | `1` (`0101 & 0011 = 0001`) |
| `|` | OR | `a | b` | `7` (`0101 | 0011 = 0111`) |
| `~` | NOT | `~a` | `-6` (`~0101 = 1010`) |
| `<<` | Left Shift | `a << 2` | `20` (`0101 → 10100`) |
| `>>` | Right Shift | `a >> 1` | `2` (`0101 → 0010`) |
| `>>>` | Zero-Fill Right Shift | `-16 >>> 2` | `1073741820` |
---
# When to Use Bitwise Operators?
✔ Optimizing performance-critical code (e.g., graphics, cryptography).
✔ Working with binary flags/permissions .
✔ Low-level data manipulation (e.g., network protocols).