Bitwise operators work directly on the binary representation of integers, one bit at a time. They are the foundation of flags, masks, hashing, compression and low-level protocol parsing. This reference lists every operator with its truth table, gives you a live calculator, and collects the masking patterns you reach for most.
How it works
Each binary operator combines the bits of two numbers position by position:
&(AND) yields 1 only when both bits are 1 — used to mask off bits.|(OR) yields 1 when either bit is 1 — used to set bits.^(XOR) yields 1 when the bits differ — used to toggle bits.~(NOT) inverts every bit; in two’s complement~xequals-(x + 1).
Shifts move the whole pattern: x << n multiplies by 2^n, x >> n divides by
2^n while preserving sign, and x >>> n divides treating the value as
unsigned. The shift count is taken mod 32 on 32-bit operations.
Example
To pack a true/false flag into bit 3 of a byte and read it back:
let flags = 0;
flags |= (1 << 3); // set bit 3 → 0b0000_1000 = 8
const isOn = (flags >> 3) & 1; // read bit 3 → 1
flags &= ~(1 << 3); // clear bit 3 → 0
Notes
x & (x - 1)clears the lowest set bit; counting how many times you can do this gives the population count (number of set bits).x & -xisolates the lowest set bit, handy for Fenwick/BIT structures.- A value is a power of two exactly when
x > 0 && (x & (x - 1)) === 0. - In JavaScript bitwise operators coerce to signed 32-bit integers, so very large
values lose precision — switch to
BigIntfor 64-bit work.