Bitwise operators in JavaScript are tools that allow you to work directly with the binary (bit-level) representation of numbers. This might sound complex, but once you grasp the basics, bitwise operations can be incredibly powerful—especially in tasks like performance optimization, flags management, encryption, and graphics.
JavaScript bitwise operators work on 32-bit integers, meaning any number you use will first be converted into a 32-bit binary number. Each bit is then compared or manipulated depending on the operator.
Here are the core bitwise operators in JavaScript:
Operator | Name | Symbol |
---|---|---|
AND | Bitwise AND | & |
OR | Bitwise OR | ` |
XOR | Bitwise XOR | ^ |
NOT | Bitwise NOT | ~ |
LEFT SHIFT | Left Shift | << |
RIGHT SHIFT | Right Shift | >> |
UNSIGNED RIGHT SHIFT | Unsigned Right Shift | >>> |
&
)This compares each bit of two numbers and returns 1 only if both bits are 1.
jsCopyEdit5 & 3
// 5 = 0101
// 3 = 0011
// --------
// 0001 = 1
So, 5 & 3
returns 1
.
|
)Returns 1 if at least one of the bits is 1.
jsCopyEdit5 | 3
// 0101
// 0011
// -----
// 0111 = 7
So, 5 | 3
returns 7
.
^
)Returns 1 only if the bits are different.
jsCopyEdit5 ^ 3
// 0101
// 0011
// -----
// 0110 = 6
So, 5 ^ 3
returns 6
.
~
)Inverts each bit: 0 becomes 1, and 1 becomes 0.
jsCopyEdit~5
// 5 = 00000000 00000000 00000000 00000101
// ~ = 11111111 11111111 11111111 11111010
// This is -6 in 32-bit two's complement
So, ~5
returns -6
.
<<
)Shifts the bits to the left, adding 0s on the right. Each shift left multiplies the number by 2.
jsCopyEdit5 << 1 // 0101 becomes 1010 = 10
5 << 2 // 0101 becomes 10100 = 20
>>
)Shifts bits to the right. Fills the left with the original number’s sign bit (preserves the sign).
jsCopyEdit10 >> 1 // 1010 becomes 0101 = 5
-10 >> 1 // Fills with 1s = -5
>>>
)Similar to >>
, but fills the left with 0s, ignoring the sign.
jsCopyEdit-10 >>> 1 // Converts to large positive number
Suppose we’re managing user permissions with flags:
jsCopyEditconst READ = 1; // 0001
const WRITE = 2; // 0010
const EXECUTE = 4; // 0100
let userPermission = READ | WRITE; // 0001 | 0010 = 0011 (3)
function canWrite(perm) {
return (perm & WRITE) !== 0;
}
canWrite(userPermission); // true