Bitwise operators in JavaScript are tools that allow you to work directly with the binary (bit-level) representation of numbers. This might sound complex, but once you grasp the basics, bitwise operations can be incredibly powerful—especially in tasks like performance optimization, flags management, encryption, and graphics.

What Are Bitwise Operators?

JavaScript bitwise operators work on 32-bit integers, meaning any number you use will first be converted into a 32-bit binary number. Each bit is then compared or manipulated depending on the operator.

Here are the core bitwise operators in JavaScript:

OperatorNameSymbol
ANDBitwise AND&
ORBitwise OR`
XORBitwise XOR^
NOTBitwise NOT~
LEFT SHIFTLeft Shift<<
RIGHT SHIFTRight Shift>>
UNSIGNED RIGHT SHIFTUnsigned Right Shift>>>

1. Bitwise AND (&)

This compares each bit of two numbers and returns 1 only if both bits are 1.

jsCopyEdit5 & 3
// 5 = 0101
// 3 = 0011
// --------
//     0001 = 1

So, 5 & 3 returns 1.


2. Bitwise OR (|)

Returns 1 if at least one of the bits is 1.

jsCopyEdit5 | 3
// 0101
// 0011
// -----
// 0111 = 7

So, 5 | 3 returns 7.


3. Bitwise XOR (^)

Returns 1 only if the bits are different.

jsCopyEdit5 ^ 3
// 0101
// 0011
// -----
// 0110 = 6

So, 5 ^ 3 returns 6.


4. Bitwise NOT (~)

Inverts each bit: 0 becomes 1, and 1 becomes 0.

jsCopyEdit~5
// 5 = 00000000 00000000 00000000 00000101
// ~ = 11111111 11111111 11111111 11111010
// This is -6 in 32-bit two's complement

So, ~5 returns -6.


5. Left Shift (<<)

Shifts the bits to the left, adding 0s on the right. Each shift left multiplies the number by 2.

jsCopyEdit5 << 1 // 0101 becomes 1010 = 10
5 << 2 // 0101 becomes 10100 = 20

6. Right Shift (>>)

Shifts bits to the right. Fills the left with the original number’s sign bit (preserves the sign).

jsCopyEdit10 >> 1 // 1010 becomes 0101 = 5
-10 >> 1 // Fills with 1s = -5

7. Unsigned Right Shift (>>>)

Similar to >>, but fills the left with 0s, ignoring the sign.

jsCopyEdit-10 >>> 1 // Converts to large positive number

Why Use Bitwise Operators?

  1. Performance – Bitwise operations are low-level and extremely fast.
  2. Flags and Permissions – You can use bits to track multiple true/false states compactly.
  3. Graphics/Color Manipulation – Often used in pixel-level operations.
  4. Encoding/Decoding Data – Used in compression and cryptography.

Real Example – Flagging Options

Suppose we’re managing user permissions with flags:

jsCopyEditconst READ = 1;       // 0001
const WRITE = 2;      // 0010
const EXECUTE = 4;    // 0100

let userPermission = READ | WRITE; // 0001 | 0010 = 0011 (3)

function canWrite(perm) {
  return (perm & WRITE) !== 0;
}

canWrite(userPermission); // true

Summary