JavaScript Bitwise Operators

Bitwise operators in JavaScript operate on the binary representations of numbers. Here's a breakdown of each bitwise operator and how it works:

Bitwise AND (`&`)

The bitwise AND operator performs a bitwise AND operation. Each bit in the result is set to 1 if both corresponding bits in the operands are 1.


let a = 5; // 0101 in binary
let b = 3; // 0011 in binary
let result = a & b; // 0001 in binary, which is 1 in decimal

                

Result: 1

Bitwise OR (`|`)

The bitwise OR operator performs a bitwise OR operation. Each bit in the result is set to 1 if at least one of the corresponding bits in the operands is 1.


let result = a | b; // 0111 in binary, which is 7 in decimal

                

Result: 7

Bitwise XOR (`^`)

The bitwise XOR operator performs a bitwise XOR operation. Each bit in the result is set to 1 if only one of the corresponding bits in the operands is 1.


let result = a ^ b; // 0110 in binary, which is 6 in decimal

                

Result: 6

Bitwise NOT (`~`)

The bitwise NOT operator performs a bitwise NOT operation. Each bit in the result is inverted (0 becomes 1 and 1 becomes 0).


let result = ~a; // 1010 in binary (two's complement), which is -6 in decimal

                

Result: -6

Bitwise Left Shift (`<<`)< /h2>

The bitwise left shift operator shifts the bits of the first operand to the left by the number of positions specified by the second operand.


let result = a << 1; // 1010 in binary, which is 10 in decimal

                

Result: 10

Bitwise Right Shift (`>>`)

The bitwise right shift operator shifts the bits of the first operand to the right by the number of positions specified by the second operand.


let result = a >> 1; // 0010 in binary, which is 2 in decimal

                

Result: 2

Unsigned Right Shift (`>>>`)

The unsigned right shift operator shifts the bits of the first operand to the right by the number of positions specified by the second operand, always shifting in zeros.


let result = a >>> 1; // 0010 in binary, which is 2 in decimal

                

Result: 2