Logical Operators
You'll learn: How to combine multiple true/false conditions using AND, OR, and NOT to make more powerful decisions in your code.
What Are Logical Operators?
You already know comparison operators like > and == give you boolean results (true or false). But what if you need to check multiple conditions at once? That's where logical operators come in.
The three fundamental logical operators are:
- AND – both conditions must be true
- OR – at least one condition must be true
- NOT – flips true to false (and vice versa)
How They Work
Think of AND like a security door that needs both a keycard AND a fingerprint. If either is missing, you can't enter.
OR is like choosing a dessert: ice cream OR cake makes you happy—you just need one (though both work too!).
NOT is simply the opposite: if it's NOT raining, then it must be dry.
In Practice
Suppose you're checking if someone can vote. They must be at least 18 years old AND a citizen:
age >= 18 AND isCitizen == true
Or maybe you're checking if a store is closed. It closes if it's a holiday OR past 9 PM:
isHoliday == true OR currentHour >= 21
And to check if someone is NOT an admin:
NOT (isAdmin == true)
You can combine these to build complex conditions that mirror real-world logic!
Key Takeaway: Logical operators (AND, OR, NOT) let you combine boolean expressions into complex conditions, enabling your programs to make sophisticated decisions based on multiple factors at once.