Bitwise AND (&)
You'll learn how the bitwise AND operator compares two numbers bit-by-bit and produces a result where each bit is 1 only if both corresponding bits are 1.
What Is Bitwise AND?
The & operator takes two numbers, converts them to their binary (0s and 1s) representations, and compares each pair of bits in the same position. The result has a 1 in a position only when both input bits at that position are 1. If either bit is 0, the result bit is 0.
Think of it like two security guards who both need to approve entry—if both say "yes" (1), you get in (result is 1). If either says "no" (0), you're blocked (result is 0).
How It Works
Let's say you perform 5 & 3:
// 5 in binary: 0101
// 3 in binary: 0011
// Result (&): 0001 (which is 1 in decimal)
console.log(5 & 3); // 1
The operator compares bit-by-bit:
- Position 0 (rightmost): 1 & 1 = 1
- Position 1: 0 & 1 = 0
- Position 2: 1 & 0 = 0
- Position 3: 0 & 0 = 0
Result: 0001 = 1
Another example:
// 12 in binary: 1100
// 10 in binary: 1010
// Result (&): 1000 (which is 8)
console.log(12 & 10); // 8
When Is It Useful?
The bitwise AND is commonly used to check if specific bits are set, create masks, or perform low-level operations where you need precise bit control.
Key Takeaway: The bitwise AND (&) operator compares two numbers bit-by-bit, returning 1 only when both corresponding bits are 1, otherwise 0.