JavaScript Bitwise Operators


What Are Bitwise Operators?

Bitwise operators perform operations on binary representations of integers. These operations work at the bit level, making them useful for low-level programming, flags, and performance optimization.

All bitwise operations convert operands to 32-bit signed integers in binary.


List of Bitwise Operators

Operator Name Description Example Binary of Example
& AND Sets each bit to 1 if both bits are 1 5 & 3 0101 & 0011 = 0001 → 1
` ` OR Sets each bit to 1 if one of two is 1 `5
^ XOR (exclusive OR) Sets each bit to 1 if only one is 1 5 ^ 3 0101 ^ 0011 = 0110 → 6
~ NOT (complement) Inverts all bits ~5 ~0000 0101 = 1111 1010 → -6
<<< /td> Left Shift Shifts bits to the left, filling with 0 5 << 1 0101 << 1=1010 → 10
>> Right Shift Shifts bits to the right, keeping sign bit 5 >> 1 0101 >> 1 = 0010 → 2
>>> Zero-fill Right Shift Shifts bits right and fills with 0 (no sign) -5 >>> 1 depends on 32-bit binary

<

1. AND (&)

console.log(5 & 3); // Output: 1
// 5 = 0101, 3 = 0011, result = 0001 = 1


2. OR (|)

console.log(5 | 3); // Output: 7
// 0101 | 0011 = 0111


3. XOR (^)

console.log(5 ^ 3); // Output: 6
// 0101 ^ 0011 = 0110


4. NOT (~)

console.log(~5); // Output: -6
// ~0101 = 1010 (in 2’s complement: -6)


5. Left Shift (<<)< /h3>
console.log(5 << 1); // Output: 10
// 0101 << 1 = 1010


6. Right Shift (>>)

console.log(5 >> 1); // Output: 2
// 0101 >> 1 = 0010


7. Zero-Fill Right Shift (>>>)

console.log(-5 >>> 1); // Output: 2147483645

Explanation:

  • -5 in 32-bit binary = 11111111111111111111111111111011
  • Right shift and fill with zero: 01111111111111111111111111111101

Summary Table

Expression Binary Result
5 & 3 0101 & 0011 1
`5 3` `0101
5 ^ 3 0101 ^ 0011 6
~5 ~00000101 -6
5 << 1 0101 << 1 10
5 >> 1 0101 >> 1 2
-5 >>> 1 32-bit binary shifted 21474836 45

Use Case: Flagging System


Bitwise operators are used in permission systems:

const READ = 1; // 0001
const WRITE = 2; // 0010
const EXECUTE = 4; // 0100
let permission = READ | WRITE; // 0001 | 0010 = 0011
console.log(permission & READ); // Output: 1 (has READ)
console.log(permission & EXECUTE); // Output: 0 (no EXECUTE)