1. Logical operators
So far, we've been checking one condition at a time with if, else if, and else. But what if we want something to happen only when multiple conditions are true? Or when at least one condition is true? That's where logical operators come in.
2. ARE, OR, and NOT
Logical operators let us combine multiple conditions into one statement. The three main ones are AND, OR, and NOT.
3. AND
We use `&&`, which stands for "and", when we want both conditions to be true. For example, imagine we're checking if a user is both logged in and has admin access. We'd write something like `if (isLoggedIn && isAdmin)`. The code only runs if both of those are true.
4. OR
Next, we have `||`, which means "or". This lets us run code when at least one condition is `true`. So if we want to allow access if someone is an admin or a moderator, we'd write `if (isAdmin || isModerator)`. If either condition is true, the block runs.
5. NOT
Finally, there's `!`, which means "not". This flips a condition. For example, `!isLoggedIn` means "if the user is not logged in."
6. Logical operators and if-else if-else
Logical operators are especially helpful when we're dealing with complex decisions. We can combine them with `if`, `else if`, and `else` to build more flexible control flows.
Let's say we're evaluating a student's performance. We might check if their score is high and attendance is good before showing a message like `"Excellent work!"`. Or we might use multiple else if blocks to check various combinations of scores and attendance.
7. Recap
These tools help us write code that responds more precisely to what's happening in our program. They give us control over not just what happens but when it happens - and under exactly which conditions. Here is a recap to help you.
8. Let's practice!
Now, you'll get to work with logical operators to make sure multiple conditions are satisfied and then build out a more complete workflow using multiple `else if` statements. Let's get started!