Bitwise Operators

Working directly on the bits of a 32-bit integer -- flags, masks and fast tricks.

Syntaxa & b a | b a ^ b ~a a << n a >> n a >>> n

Bitwise operators convert their operands to 32-bit signed integers and work bit by bit: & (AND), | (OR), ^ (XOR), ~ (NOT), and the shifts <<, >>, >>>.

The everyday use: flags

Pack many booleans into one number. Each bit is a flag; | sets, & tests, ^ toggles.

const READ = 1, WRITE = 2, EXEC = 4;
let perms = READ | WRITE;      // 3
const canWrite = (perms & WRITE) !== 0; // true

Handy tricks

  • n & 1 tests oddness faster than %.
  • x ^ y ^ x === y -- XOR is its own inverse.
  • Unsigned shift >>> is the only operator that yields a value above 2**31.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Store multiple boolean feature flags as bits in a single integer to reduce database columns.
  • Use bitwise AND with a mask to check whether a specific permission bit is set in a permissions integer.
  • Apply a bitwise OR to combine RGB channel values into a single packed color integer.

More examples

Check a permission bit with AND

Defines permission bit flags and uses & to test whether a specific bit is set in the user's permissions.

Example Β· js
const READ  = 0b001; // 1
const WRITE = 0b010; // 2
const EXEC  = 0b100; // 4
const userPerms = READ | WRITE; // 3
console.log((userPerms & WRITE) !== 0); // true – has write
console.log((userPerms & EXEC)  !== 0); // false – no exec

Fast floor with bitwise OR

Uses |0 as a fast integer truncation trick; equivalent to Math.floor for positive numbers.

Example Β· js
const x = 4.9;
console.log(x | 0);          // 4 – faster integer truncation
console.log(Math.floor(x));  // 4

Toggle a bit with XOR

XOR toggles a specific bit: applying the same mask twice returns to the original state.

Example Β· js
let flags = 0b0101;
const MASK = 0b0010;
flags ^= MASK; // toggle bit 1
console.log(flags.toString(2)); // "111"
flags ^= MASK; // toggle again
console.log(flags.toString(2)); // "101"

Discussion

  • Be the first to comment on this lesson.
Bitwise Operators β€” JavaScript | SoundsCode