Bitwise operators work on 32-bit numbers. Any numeric operand in a bitwise operation is converted into a 32-bit binary number (a sequence of 0s and 1s) before the operation is performed. The result is then converted back to a standard JavaScript number.
Here are the common bitwise operators in JavaScript:
| Operator | Name | Description |
|---|---|---|
& |
AND | Sets each bit to 1 if both bits are 1 |
| |
OR | Sets each bit to 1 if one of two bits is 1 |
^ |
XOR | Sets each bit to 1 if only one of two bits is 1 |
~ |
NOT | Inverts all the bits (0 becomes 1, 1 becomes 0) |
<< |
Left Shift | Shifts bits left by pushing zeros in from the right |
>> |
Right Shift | Shifts bits right (maintains sign bit) |
>>> |
Zero-fill Right Shift | Shifts bits right by pushing zeros in from the left |
Bitwise operations might seem confusing at first because we don't usually think in binary. Let's look at a simple example using Bitwise AND (&) with the numbers 5 and 1.
0000010100000001let result = 5 & 1; // Binary: 00000001 (Decimal: 1)
console.log(result); // 1
In this case, only the last bit is 1 in both numbers, so only that bit remains 1 in the result.
Bitwise operators are not used very often in daily web development, but they are extremely fast and useful in specific areas:
The bitwise NOT operator inverts a number. Because JavaScript uses signed 32-bit integers,
inverting a number x results in -(x + 1).
console.log(~5); // -6
console.log(~10); // -11
&, |, and ^ compare
corresponding bits<<, >>) move bits left or right