Here are concise notes on using bitwise operators in JavaScript โ€” useful for interviews and coding practice:


๐Ÿ”น Basics

JavaScript stores numbers as 64-bit floating point, but bitwise operators work on 32-bit signed integers.

  • Signed 32-bit integer โ†’ range: -2,147,483,648 to 2,147,483,647

  • Bitwise ops truncate numbers to 32-bit, then back to JS Number.


๐Ÿ”น Common Bitwise Operators

OperatorSymbolExampleMeaning
AND&5 & 3 = 1Bit is 1 only if both bits are 1
OR|5 | 3 = 7Bit is 1 if at least one bit is 1
XOR^5 ^ 3 = 6Bit is 1 if bits differ
NOT~~5 = -6Flips all bits (2โ€™s complement)
Left Shift<<5 << 1 = 10Shift left, fill with 0
Right Shift (Sign-propagating)>>5 >> 1 = 2Shift right, keep sign bit
Unsigned Right Shift>>>-5 >>> 1 = 2147483645Shift right, fill with 0

๐Ÿ”น Useful Tricks

  1. Check even/odd
let x = 7;
console.log(x & 1 ? "Odd" : "Even"); // Odd
  1. Swap two numbers without temp
let a = 5, b = 9;
a = a ^ b;
b = a ^ b;
a = a ^ b;
console.log(a, b); // 9, 5
  1. Multiply or divide by 2
console.log(5 << 1); // 10  (5 * 2)
console.log(20 >> 2); // 5  (20 / 4)
  1. Check if k-th bit is set
let n = 13; // 1101
let k = 2;  // (0-indexed from right)
console.log((n & (1 << k)) !== 0); // true (bit is set)
  1. Set a bit
n = n | (1 << k);
  1. Clear a bit
n = n & ~(1 << k);
  1. Toggle a bit
n = n ^ (1 << k);
  1. Count set bits (Brian Kernighanโ€™s Algo)
function countBits(n) {
  let count = 0;
  while (n > 0) {
    n = n & (n - 1); // clears the lowest set bit
    count++;
  }
  return count;
}
console.log(countBits(29)); // 4 (11101 has 4 set bits)

๐Ÿ”น Common Use Cases

  • Checking even/odd quickly

  • Efficient multiplication/division by powers of 2

  • Bit masking (checking flags/permissions)

  • Swapping numbers without temp variable

  • Subset generation problems

  • Low-level optimizations in algorithms