Bitwise Operators and Type Coercion
What you'll learn: How JavaScript automatically converts values to 32-bit integers before performing bitwise operations.
The Hidden Conversion
When you use bitwise operators like &, |, ^, ~, <<, >>, or >>>, JavaScript doesn't work with the values exactly as you write them. Behind the scenes, it performs an automatic conversion: every operand is first coerced to a 32-bit signed integer.
This means:
- Floating-point numbers lose their decimal parts
- Numbers outside the 32-bit range wrap around
- Non-numbers get converted to numbers first, then to 32-bit integers
- Even though JavaScript's normal numbers are 64-bit floats, bitwise operations force everything into a 32-bit world
How the Conversion Works
Think of it like passing luggage through airport security: no matter what size bag you bring, it must fit through a standard-sized scanner. Similarly, all values must "fit" the 32-bit integer format before bitwise operations can touch them.
Examples of the coercion:
5.7 & 3; // 5.7 → 5, then 5 & 3 → 1
true | false; // true → 1, false → 0, then 1 | 0 → 1
"10" & "3"; // "10" → 10, "3" → 3, then 10 & 3 → 2
null << 2; // null → 0, then 0 << 2 → 0
Notice how decimals get truncated, booleans become 1 or 0, strings are parsed as numbers, and null becomes 0—all before the bitwise operator executes.
Key Takeaway: Bitwise operators always convert their operands to 32-bit signed integers first, which means decimal places vanish and non-numeric values undergo type coercion before the actual bitwise operation occurs.