JavaScript Bitwise Operators
JavaScript Bitwise Operators
JavaScript is a powerful programming language that not only works with numbers, strings, and objects, but also provides tools to work at the binary level. These tools are known as Bitwise Operators.
While most beginners work with arithmetic and logical operators, bitwise operators allow developers to manipulate the actual bits of numbers. This is useful in scenarios like working with flags, encryption, compression, and performance optimization.
Bitwise operators in JavaScript perform operations directly on the binary representations of integers. Every number in JavaScript is internally represented in 32-bit signed integer form for bitwise operations. These operators allow you to work on bits (0s and 1s) rather than the entire number.
Bitwise Operators
Some of the bitwise operators are as follows:
Operator | Description |
---|---|
& | Bitwise AND – Returns 1 only if both bits are 1. |
| | Bitwise OR – Returns 1 if at least one bit is 1. |
^ | Bitwise XOR – Returns 1 if the bits are different. |
~ | Bitwise NOT – Inverts all the bits (0 becomes 1, 1 becomes 0). |
<< | Left Shift – Shifts bits to the left and adds zeros on the right. |
>> | Right Shift – Shifts bits to the right and preserves the sign. |
>>> | Unsigned Right Shift – Shifts bits to the right and fills with zeros. |
Example Code
<script>
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
console.log("a & b (AND):", a & b); // 0101 & 0011 = 0001 (1)
console.log("a | b (OR):", a | b); // 0101 | 0011 = 0111 (7)
console.log("a ^ b (XOR):", a ^ b); // 0101 ^ 0011 = 0110 (6)
console.log("~a (NOT):", ~a); // ~0101 = 1010 (-6 in decimal)
console.log("a << 1 (Left Shift):", a << 1); // 0101 << 1 = 1010 (10)
console.log("a >> 1 (Right Shift):", a >> 1); // 0101 >> 1 = 0010 (2)
console.log("a >>> 1 (Unsigned Right Shift):", a >>> 1); // 0101 >>> 1 = 0010 (2)
</script>