const a = 5; // binary 0101 const b = 3; // binary 0011 const result = a & b; console.log(result);
The bitwise AND operator compares each bit of two numbers and returns 1 only if both bits are 1.
5 in binary is 0101, 3 is 0011. ANDing them gives 0001 which is 1 in decimal.
const x = 4; const y = x << 2; console.log(y);
Left shifting a number by 2 bits is the same as multiplying it by 4.
So 4 << 2 equals 4 * 4 = 16.
let num = 10; num = num ^ 5; num = num ^ 5; console.log(num);
XOR operation toggles bits. Doing XOR twice with the same number restores the original value.
So num ends up as 10 again.
Bit manipulation works directly on the binary representation of numbers, often using simple CPU instructions that are faster than arithmetic operations.
The least significant bit (rightmost bit) is 0 for even numbers and 1 for odd numbers.
Using bitwise AND with 1 isolates this bit.
