Lesson 8 / 38

Conditionals: if/else & switch

Branching logic, and a compact alternative.

if / else if / else

Conditions run top to bottom; the first truthy one wins.

const hour = 14;
if (hour < 12) {
  console.log("Morning");
} else if (hour < 18) {
  console.log("Afternoon");
} else {
  console.log("Evening");
}

Output:

Afternoon

switch statement

Good for many discrete values on one variable — don't forget break, or execution falls through.

switch (day) {
  case "Mon":
  case "Tue":
    console.log("Early week");
    break;
  default:
    console.log("Later");
}

Ternary operator

condition ? valueIfTrue : valueIfFalse — a compact if/else for use inside an expression, e.g. const label = age >= 18 ? "adult" : "minor";