JavaScript Bitwise Operators and 32-Bit Numbers
Quick answer
Bitwise operations manipulate binary positions of integer representations. For Number operands most bitwise operators first convert values to 32-bit integers; they are not general-purpose large-number arithmetic.
How it works
& keeps shared set bits, | combines them, ^ keeps differing bits and ~ flips all bits. << shifts left, >> shifts right with sign extension and >>> shifts right with zero fill. Number shift counts use the low five bits (modulo 32 after unsigned conversion). BigInt supports signed bitwise operations without 32-bit truncation, but not >>>. Avoid mixing Number and BigInt. Compound forms &=, |=, ^=, <<=, >>=, and >>>= store the corresponding bitwise result.
const read = 1;const write = 2;const permissions = read | write;console.log(permissions);console.log((permissions & write) === write);Expected output in Node.js:
3trueIndependent bit flags combine and can be tested with a mask.
console.log(-8 >> 1);console.log(-8 >>> 1);console.log(1 << 32);Expected output in Node.js:
-421474836441Signed and unsigned shifts differ; the Number shift count wraps at 32.
Common mistakes
Do not confuse & with && or | with ||. Parenthesize mask tests: (flags & mask) === mask. Bitwise coercion can discard high bits and fractions, so do not use it as a general integer conversion.
Practice
Check whether all bits in a small nonnegative mask are present.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript Bitwise Operators and 32-Bit Numbers — Knowledge Check
Apply the taught concept and reason about the result.
What is 7 & 3?
What is 4 bitwise-OR 1?
What is -8 >> 1?
What is 1 << 32 with Number operands?
Which operator rejects BigInt operands?