Logical Operators in Conditions
You'll learn how to use && and || inside if statements to create complex, multi-part conditions that make smarter decisions.
The Core Idea
Up until now, you've seen logical operators (&&, ||, !) used on their own. But their real power shines when you use them inside conditional statements like if. This lets you check multiple things at once before deciding what code to run.
Think of it like a bouncer at a club checking both your ID and your invitation—two separate conditions that must both be true before you get in.
Using && in Conditions
let age = 25;
let hasTicket = true;
if (age >= 18 && hasTicket) {
console.log("Welcome to the concert!");
}
Both conditions must be true for the code block to execute. If either is false, the whole condition fails.
Using || in Conditions
let isWeekend = true;
let isHoliday = false;
if (isWeekend || isHoliday) {
console.log("You can sleep in!");
}
Only one condition needs to be true. This is perfect for "either/or" scenarios.
Combining Multiple Operators
let temperature = 75;
let isSunny = true;
let hasUmbrella = false;
if ((temperature > 70 && isSunny) || hasUmbrella) {
console.log("Good day for a walk!");
}
Use parentheses to control which conditions are evaluated together, just like in math.
Why This Matters
Without logical operators, you'd need deeply nested if statements or repeated code. Logical operators let you express complex decision-making clearly and concisely in a single condition.
Key Takeaway: Use && when all conditions must be true, || when any condition can be true, and combine them inside if statements to create sophisticated program logic.