Skip to main content
Advertisement

3.1 Conditional Statements

What are Conditional Statements?

Conditional statements execute different code blocks based on given conditions. JavaScript supports if/else, switch, and the ternary operator.


if / else

const temperature = 25;

if (temperature > 30) {
console.log("It's hot!");
} else if (temperature > 20) {
console.log("Nice weather.");
} else if (temperature > 10) {
console.log("A bit chilly.");
} else {
console.log("It's cold!");
}
// "Nice weather."

Compound Conditions

const age = 22;
const hasID = true;

// AND: both must be true
if (age >= 18 && hasID) {
console.log("Entry permitted.");
}

// OR: at least one true
const isWeekend = true;
const isHoliday = false;

if (isWeekend || isHoliday) {
console.log("Day off!");
}

// NOT: negation
const isLoggedIn = false;
if (!isLoggedIn) {
console.log("Please log in.");
}

switch Statement

More readable than if-else chains when comparing multiple cases.

const day = "Monday";

switch (day) {
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
console.log("Weekday.");
break;
case "Saturday":
case "Sunday":
console.log("Weekend!");
break;
default:
console.log("Unknown day");
}

Watch for Fall-through

// Using return to keep switch clean
function getDayType(day) {
switch (day) {
case "Saturday":
case "Sunday":
return "Weekend";
default:
return "Weekday";
}
}

Ternary Operator

For simple conditional expressions.

const age = 18;
const status = age >= 18 ? "adult" : "minor";
console.log(status); // "minor"

// In template literals
const score = 85;
const result = `Score: ${score}${score >= 60 ? "Pass" : "Fail"}`;
console.log(result); // "Score: 85 — Pass"

// Chained ternary (mind readability)
const grade = score >= 90 ? "A"
: score >= 80 ? "B"
: score >= 70 ? "C"
: "F";

Short-Circuit Evaluation Patterns

// && pattern: execute only when condition is true
const isAdmin = true;
isAdmin && console.log("Show admin menu");

// || pattern: default value
const userName = "" || "Anonymous";
const port = process.env.PORT || 3000;

// ?? pattern: default only for null/undefined
const config = userConfig ?? defaultConfig;
const timeout = options.timeout ?? 5000;

Early Return Pattern

Flattens code by handling edge cases first.

// Bad: excessive nesting
function processUser(user) {
if (user) {
if (user.isActive) {
if (user.hasPermission) {
return doProcess(user);
} else {
return "No permission";
}
} else {
return "Inactive user";
}
} else {
return "No user";
}
}

// Good: early return flattening
function processUser(user) {
if (!user) return "No user";
if (!user.isActive) return "Inactive user";
if (!user.hasPermission) return "No permission";

// Main logic is clearly visible
return doProcess(user);
}

Pro Tips

Simplify Conditions with Variables

// Bad: long condition, hard to understand
if (user.age >= 18 && user.isActive && !user.isBanned && user.subscription === "premium") {
showPremiumContent();
}

// Good: express intent with names
const isAdult = user.age >= 18;
const isEligible = user.isActive && !user.isBanned;
const isPremium = user.subscription === "premium";

if (isAdult && isEligible && isPremium) {
showPremiumContent();
}

Strategy Pattern to Replace Conditionals

const discountStrategies = {
vip: (price) => price * 0.7,
member: (price) => price * 0.9,
student: (price) => price * 0.8,
guest: (price) => price,
};

function calculatePrice(price, userType) {
const strategy = discountStrategies[userType] ?? discountStrategies.guest;
return strategy(price);
}

console.log(calculatePrice(10000, "vip")); // 7000
console.log(calculatePrice(10000, "student")); // 8000
console.log(calculatePrice(10000, "unknown")); // 10000
Advertisement