Bitwise operators are JavaScript’s way of saying, "Let's talk in binary!" If you've ever wondered how computers really think (spoiler: they don’t), this is it! These operators let you manipulate numbers at the binary level—yes, the ones and zeroes that make up everything in your digital life. Get ready for some brain gymnastics!
1. AND (&
)
The bitwise AND operator compares each bit of two numbers and returns 1
if both bits are 1
, otherwise, it returns 0
. Think of it as the handshake of numbers: both parties must agree!
console.log(5 & 3); // 1 (Why? Because 5 is 101, 3 is 011, and 101 & 011 is 001)
Real-life analogy: You and your friend both want pizza. If you both say "yes," you get pizza (1
). If either says "no," no pizza (0
).
2. OR (|
)
The bitwise OR operator returns 1
if at least one of the compared bits is 1
.
console.log(5 | 3); // 7 (Because 5 is 101, 3 is 011, and 101 | 011 is 111)
Real-life analogy: If either you or your friend says "yes" to pizza, you get pizza!
3. XOR (^
)
The bitwise XOR (exclusive OR) operator returns 1
if the compared bits are different.
console.log(5 ^ 3); // 6 (Because 5 is 101, 3 is 011, and 101 ^ 011 is 110)
Real-life analogy: If one of you wants pizza and the other doesn’t, you flip a coin and whoever wins gets pizza.
4. NOT (~
)
The bitwise NOT operator flips every bit. Think of it as JavaScript saying, "Whatever you thought, think again!"
console.log(~5); // -6 (Because 5 is 00000101 in binary, and ~ flips it to 11111010, which is -6 in two’s complement.)
Real-life analogy: You said "I’ll start dieting tomorrow." JavaScript said "Nope, you’re eating double today."
5. Left Shift (<<
)
Shifts the bits to the left by a certain number of places, adding zeros at the right. Equivalent to multiplying by 2.
console.log(5 << 2); // 20 (Because 5 is 101, shifting left twice gives 10100, which is 20 in decimal.)
Real-life analogy: Doubling your salary by simply sliding the decimal point. If only real life worked this way!
6. Right Shift (>>
)
Moves the bits to the right, discarding bits on the right. Equivalent to dividing by 2.
console.log(20 >> 2); // 5 (Because 20 is 10100, shifting right twice gives 101, which is 5 in decimal.)
Real-life analogy: You had a whole pizza but had to share half of it every time you moved down the line. Eventually, you’re left with crumbs.
7. Zero-Fill Right Shift (>>>
)
Similar to >>
, but always fills the leftmost bits with zeros instead of preserving the sign.
console.log(-20 >>> 2); // 1073741819 (Because JavaScript loves chaos!)
Real-life analogy: Imagine moving to another country but leaving all your emotional baggage behind. Fresh start!
Conclusion
Bitwise operators are useful in low-level programming, encryption, and feeling really smart when you explain them to your friends. If binary math makes your brain hurt, just remember: computers only see 1s and 0s, and now... so do you!
0 Comments