JavaScript Numbers are 64-bit floats, but the bitwise operators (&, |, ^, ~, <<, >>, >>>) work on 32-bit integers. Each operand goes through a conversion first:
ToNumber, so'12' | 0is12and'abc' | 0is0.ToIntegerOrInfinity: truncate toward zero;NaNbecomes0.ToFixedSizeInteger(…, 32):±Infinitybecomes0; everything else is taken modulo 2³².ToInt32then reads the result as signed two's complement (−2³¹ to 2³¹ − 1);ToUint32reads it as unsigned (0 to 2³² − 1).
The operator works on those 32 bits, and the result is a Number again:
&,|,^,~useToInt32and return a signed 32-bit value.<<and>>convert the left side withToInt32;>>copies the sign bit in from the left.>>>converts the left side withToUint32and fills with zeros, so its result is unsigned.x >>> 0is the idiom for "as uint32".- The shift count goes through
ToUint32and then modulo 32, so1 << 32is1, not0.
Consequences interviewers probe: x | 0 and ~~x truncate like Math.trunc only inside the int32 range; larger values wrap silently (2 ** 31 | 0 is −2147483648, 1e10 | 0 is 1410065408). -1 >>> 0 is 4294967295.
BigInts are different. Their &, |, ^, ~, <<, >> work on arbitrary-width two's complement, with no truncation. >>> throws a TypeError for BigInts: with no fixed width, there's no unsigned form to zero-fill. Mixing BigInt and Number in one bitwise operation also throws a TypeError.
Bitwise operators are still the right tool for bit flags, hashes, binary protocols and colour packing, as long as the values fit in 32 bits.