JS Bitwise Operators
In this page:
AND, OR, XOR
The & (AND) operator sets a result bit to 1 only when both operand bits are 1, | (OR) sets it to 1 when either bit is 1, and ^ (XOR) sets it to 1 only when the bits differ. JavaScript converts both operands to 32-bit integers before applying these operators, then converts the result back to a regular number.
Example: AND, OR, XOR
console.log(5 & 3); // 1 - AND
console.log(5 | 3); // 7 - OR
console.log(5 ^ 3); // 6 - XOR
NOT and Two's Complement
The ~ (NOT) operator flips every bit of its operand, and because JavaScript represents negative numbers using two's complement, ~n always equals -(n + 1). XOR (^) is often used alongside NOT for toggling specific bits on or off without affecting the others.
Example: NOT and Two's Complement
console.log(~5); // -6, two's complement: -(5 + 1)
Left Shift and Right Shift
The << (left shift) operator moves bits left and fills with zeros, which has the effect of multiplying by a power of two, while >> (right shift) moves bits right, dividing by a power of two and preserving the sign of negative numbers. Both are fast alternatives to multiplication or division by powers of two.
Example: Left Shift and Right Shift
console.log(4 << 1); // 8 - multiply by 2
console.log(4 >> 1); // 2 - divide by 2
console.log(-8 >> 1); // -4, sign preserved
Unsigned Right Shift
The >>> (unsigned right shift) operator also shifts bits right, but it always fills the vacated bits with zeros regardless of sign, which means it treats negative numbers as large positive numbers instead of preserving their sign. This makes it behave differently from >> specifically on negative operands.
Example: Unsigned Right Shift
console.log(-1 >> 1); // -1, sign preserved
console.log(-1 >>> 1); // large positive number, sign not preserved
Practical Bit Flags
A common real-world use of bitwise operators is packing several true/false settings into a single number, where each bit represents one flag, using OR to combine flags and AND to check if a specific flag is set. This pattern shows up in permission systems, game state, and low-level protocol handling where memory efficiency matters.
Example: Practical Bit Flags
const READ = 1; // 0b001
const WRITE = 2; // 0b010
const EXECUTE = 4; // 0b100
let permissions = READ | WRITE; // combine flags
console.log((permissions & WRITE) !== 0); // check if WRITE is set
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: