Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Operators

JavaScript bitwise operators

Reference for JavaScript bitwise operators &, |, ^, ~, <<, >> and >>>: 32-bit integer conversion, flags, masks, shifts and BigInt behavior.

Bitwise operators work on the individual bits of integers. JavaScript converts each operand to a 32-bit signed integer, performs the operation, and returns a number (also a signed 32-bit integer, except for >>>). They are handy for flags, masks, hashing and low-level data formats.

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

Try it

JS AND, OR, XOR, NOT

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Shifts and flags

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

Operator Name Description
a & b AND Each result bit is 1 if both bits are 1.
a | b OR 1 if at least one bit is 1.
a ^ b XOR 1 if the bits differ.
~a NOT Flips every bit; equals -a - 1.
a << n Left shift Moves bits left, filling with zeros.
a >> n Sign-propagating right shift Moves bits right, copying the sign bit.
a >>> n Zero-fill right shift Moves bits right, filling with zeros; the result is unsigned.

Return value: a number (a signed 32-bit integer, or an unsigned one for >>>), or a BigInt when both operands are BigInts.

Exceptions: mixing a BigInt with a regular number throws a TypeError. >>> is not allowed on BigInts (TypeError). Shifting a BigInt by a huge amount can throw a RangeError.

Usage notes

  • Operands are truncated to 32 bits. Integers outside the range wrap around, and fractions are discarded. x | 0 is a well-known (but cryptic) way to truncate; Math.trunc(x) is clearer and works with large values.
  • Shift counts use only the low 5 bits, so x << 32 equals x << 0.
  • >>> is the only way to get an unsigned result: -1 >>> 0 gives 4294967295.
  • Precedence: comparison binds tighter than &, ^ and |. Write (flags & MASK) !== 0 with parentheses, because flags & MASK !== 0 is parsed as flags & (MASK !== 0).
  • && is not &: & evaluates both sides and combines bits; && short-circuits and uses truthiness.
  • Typed arrays and DataView are better than manual shifting for binary formats.
  • Compound forms &=, |=, ^=, <<=, >>= and >>>= exist; see assignment operators.
  • Readability: use named constants for flags, and consider a plain object of booleans if you don't need the compact form.

Browser support

Supported in every browser and runtime. BigInt versions require a browser with BigInt support, which all current ones have.