Combining Logical Operators in Conditions
You'll learn how to use && and || operators together to create complex conditions and understand how short-circuit evaluation works inside if statements.
The Core Idea
You've already seen && (AND) and || (OR) operators separately. Now you can combine them within a single if condition to express more sophisticated logic. The key is understanding that JavaScript evaluates these operators left-to-right and short-circuits — it stops evaluating as soon as the result is determined.
Combining Operators
let age = 25;
let hasTicket = true;
let isVIP = false;
// Using && and || together
if ((age >= 18 && hasTicket) || isVIP) {
// Enters if: adult with ticket OR VIP (regardless of age/ticket)
}
The parentheses matter here! Without them, operator precedence could give unexpected results (remember: && has higher precedence than ||).
Short-Circuit Behavior in Action
let score = 85;
let bonus = 10;
let isPremium = true;
// This checks multiple conditions efficiently
if (score > 80 && bonus > 5 && isPremium) {
// All three must be true
// If score <= 80, JavaScript never checks bonus or isPremium
}
Think of it like a bouncer at a club checking multiple requirements: if you fail the first check (age), they don't bother checking your ticket or VIP status.
Common Pattern
let isWeekend = true;
let hasEnergy = false;
let hasFreeTime = true;
if ((isWeekend || hasFreeTime) && hasEnergy) {
// Go to the gym if you have time AND energy
}
Key Takeaway: Combine && and || in if conditions to express complex logic, use parentheses for clarity, and remember that JavaScript short-circuits evaluation as soon as the outcome is certain.