CodeBlanks Logo Icon CodeBlanks

Summary - Conditionals

JavaScript course · Beginner · Lesson 18/133

Build a day-of-the-week app using if, switch and the ternary operator.

Summary of all conditional tools

In this group you learned four conditional tools:

  • if: tests a single condition.
  • else/else if: adds branches for when the condition is false or for new conditions.
  • switch: branches on a variable's value; completed with break and default.
  • ternary: returns a value in one line with condition ? a : b.

You also saw that === strict equality is safer than == loose equality. Now combine them!

Exercise Summary task 1 - grade chain

The grade variable is a number from 0 to 100. Write an if/else if/else chain: 90 and above is 'Excellent', 70-89 is 'Good', 50-69 is 'Average', below is 'Poor'. Log each branch with console.log.

Show example solution
let grade = 75;
if (grade >= 90) {
  console.log("Excellent");
} else if (grade >= 70) {
  console.log("Good");
} else if (grade >= 50) {
  console.log("Average");
} else {
  console.log("Poor");
}

Exercise Summary task 2 - day name switch

The day variable is a number from 1 to 7 (day of the week). Use switch to log the day name: 1 'Monday', 2 'Tuesday', 3 'Wednesday'. For unknown values log 'Unknown'. Use break in each case and add a default branch.

Show example solution
let day = 2;
switch (day) {
  case 1:
    console.log("Monday");
    break;
  case 2:
    console.log("Tuesday");
    break;
  case 3:
    console.log("Wednesday");
    break;
  default:
    console.log("Unknown");
}

Test yourself

  1. When one variable needs many branches by value, which tool fits best?

    • switch statement
    • Nested ternaries
    • Several ifs with &&
    • console.log
    Show answer

    switch statement — Correct. switch is designed for branching on a single variable's value and improves readability.

  2. Match each tool to its role

    if
    Tests a single condition
    else if
    Multi-branch chain
    switch
    Branching on a single value
    ternary
    One-line conditional expression
  3. Complete the switch statement

    let grade = "A";
    switch (____) {
      case "A":
        console.log("Excellent");
        break;
      default:
        console.log("Other");
    }
    Show answer
    let grade = "A";
    switch (grade) {
      case "A":
        console.log("Excellent");
        break;
      default:
        console.log("Other");
    }

All lessons in Beginner