CPCODELAB
JavaScript

Conditionals: if/else, switch, and Ternary

8 min read

Making Decisions in Code

Conditionals let your program take different paths based on values. JavaScript offers if/else if/else, switch, and the ternary operator.

javascript
const score = 75;

if (score >= 90) {
  console.log("A");
} else if (score >= 80) {
  console.log("B");
} else if (score >= 70) {
  console.log("C");
} else {
  console.log("F");
}

switch Statement

switch compares a value against multiple cases using strict equality. Always include break (or return) to prevent fall-through to the next case — unless fall-through is intentional.

javascript
const day = "Monday";

switch (day) {
  case "Saturday":
  case "Sunday":
    console.log("Weekend");
    break;
  case "Monday":
    console.log("Start of the week");
    break;
  default:
    console.log("Weekday");
}

Ternary Operator

The ternary operator is a compact if/else for expressions. It takes the form condition ? valueIfTrue : valueIfFalse.

javascript
const age = 20;
const status = age >= 18 ? "adult" : "minor";
// "adult"

// Useful inline, but avoid nesting ternaries
const label = score >= 90 ? "A" : score >= 80 ? "B" : "C";

Deeply nested ternaries hurt readability. If you need more than one level, use if/else if or an object lookup instead.

Ready to test yourself?
Practice JavaScript— quiz & coding exercises