Bitwise OR (|)
What You'll Learn
You'll discover how the bitwise OR operator (|) combines two numbers by returning 1 whenever at least one of the corresponding bits is 1.
How Bitwise OR Works
The bitwise OR operator compares two numbers bit by bit. For each position, it asks: "Is there a 1 in either number (or both)?" If yes, the result has a 1 in that position. If both bits are 0, the result is 0.
Think of it like two light switches controlling the same bulb — if either switch (or both) is flipped on, the light turns on.
Here's the logic for each bit pair:
0 | 0=0(both off → result off)0 | 1=1(at least one on → result on)1 | 0=1(at least one on → result on)1 | 1=1(both on → result on)
Example
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011
let result = a | b; // Binary: 0111
console.log(result); // 7
Breaking it down bit by bit:
0101 (5)
| 0011 (3)
------
0111 (7)
Position by position: 0|0=0, 1|0=1, 0|1=1, 1|1=1.
When Is It Useful?
Bitwise OR is commonly used to combine flags or set specific bits to 1 without affecting others. Since any bit that's 1 in either operand becomes 1 in the result, you can "turn on" specific bits.
Key Takeaway: The bitwise OR operator (|) returns 1 for each bit position where at least one operand has a 1, making it perfect for combining binary flags.