JavaScript bitwise operations work at the binary level, performing calculations directly on the binary representation of numbers. These operations are efficient and useful for low-level programming tasks like setting flags, masking, or optimizing performance.
Bitwise Operators
1. AND (&)
- Compares each bit of two numbers and returns
1if both bits are1, otherwise0.
5 & 3; // 0101 & 0011 = 0001 (1 in decimal)
2. OR (|)
- Compares each bit of two numbers and returns
1if at least one of the bits is1.
5 | 3; // 0101 | 0011 = 0111 (7 in decimal)
3. XOR (^)
- Compares each bit of two numbers and returns
1if the bits are different, otherwise0.
5 ^ 3; // 0101 ^ 0011 = 0110 (6 in decimal)
4. NOT (~)
- Inverts all the bits of a number (1 becomes 0, and 0 becomes 1).
~5; // ~00000101 = 11111010 (-6 in decimal)
6. Right Shift (>>)
- Shifts the bits of the number to the right, preserving the sign bit (for signed numbers).
5 >> 1; // 0101 >> 1 = 0010 (2 in decimal)
-5 >> 1; // 11111011 >> 1 = 11111101 (-3 in decimal)
7. Unsigned Right Shift (>>>)
- Shifts the bits of the number to the right, filling with
0from the left (ignoring the sign bit).
5 >>> 1; // 0101 >>> 1 = 0010 (2 in decimal)
-5 >>> 1; // 11111011 >>> 1 = 01111101 (2147483645 in decimal)
Practical Use Cases
1. Masking
- Isolate specific bits using the AND operator.
const mask = 0b0011; // Binary: 0011
const value = 0b1011; // Binary: 1011
const result = value & mask; // 0011 (Binary) = 3 (Decimal)
2. Setting a Bit
- Use OR to set a specific bit.
const value = 0b1010; // Binary: 1010
const bitToSet = 0b0100; // Binary: 0100
const result = value | bitToSet; // 1110 (Binary) = 14 (Decimal)
3. Clearing a Bit
- Use AND with the NOT operator to clear a specific bit.
const value = 0b1011; // Binary: 1011
const bitToClear = 0b0100; // Binary: 0100
const result = value & ~bitToClear; // 1011 & 1011 = 1011 (Binary) = 11 (Decimal)
4. Toggling a Bit
- Use XOR to toggle a specific bit.
const value = 0b1010; // Binary: 1010
const bitToToggle = 0b0100; // Binary: 0100
const result = value ^ bitToToggle; // 1110 (Binary) = 14 (Decimal)
5. Checking a Bit
- Use AND to check if a specific bit is set.
const value = 0b1011; // Binary: 1011
const bitToCheck = 0b0010; // Binary: 0010
const isSet = (value & bitToCheck) !== 0; // true


Leave a Reply