12.3 Ternary Operator and Switch Statements

Ternary Operator and Switch Statements (15 mins)

  1. Ternary Operator:

    • The ternary operator is a shorthand way of writing an if-else statement. It simplifies conditions by allowing you to make a decision in a single line.

    • Syntax:

      condition ? expressionIfTrue : expressionIfFalse;
    • Example:

      let age = 18;
      let canVote = age >= 18 ? "Eligible to vote" : "Not eligible to vote";
      console.log(canVote);  // Outputs: "Eligible to vote"
    • The ternary operator can be useful for simplifying basic conditions that only need two outcomes.

  2. Switch Statements:

    • The switch statement is an alternative to if-else that is more suitable when you have multiple possible outcomes based on the value of a single variable or expression.

    • Syntax:

      switch (expression) {
        case value1:
          // code to run if expression === value1
          break;
        case value2:
          // code to run if expression === value2
          break;
        default:
          // code to run if no cases match
      }
    • The switch statement compares the value of an expression to multiple cases and executes the corresponding block of code for the first matching case. The break statement prevents the code from continuing to the next case.

    • Example:

      let day = 3;
      switch (day) {
        case 1:
          console.log("Monday");
          break;
        case 2:
          console.log("Tuesday");
          break;
        case 3:
          console.log("Wednesday");
          break;
        default:
          console.log("Invalid day");
      }
      • In this example, since day is 3, the output will be "Wednesday".

  3. When to Use Switch Statements:

    • Use a switch statement when you have multiple discrete values to compare, especially if they are based on a single variable or expression.

    • Switch statements make your code more readable and structured when handling many potential cases.

    • However, they are generally not used for complex conditions that require logical operators (&&, ||), where if-else or ternary operators are better suited.

Student Activity (15 mins):

Objective: Students will practice using the ternary operator to simplify simple if-else conditions and use switch statements to handle multiple cases.

Instructions:

  1. Create an HTML file (e.g., ternary_and_switch.html) and write JavaScript code that demonstrates both the ternary operator and switch statements.

    Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Ternary and Switch Statements</title>
    </head>
    <body>
      <h1>Check the Console for Output</h1>
    
      <script>
        // Ternary Operator Example
        let age = 20;
        let canVote = age >= 18 ? "Eligible to vote" : "Not eligible to vote";
        console.log(canVote);  // Outputs: "Eligible to vote"
    
        // Switch Statement Example
        let weather = "sunny";
        switch (weather) {
          case "rainy":
            console.log("Take an umbrella.");
            break;
          case "sunny":
            console.log("Wear sunglasses.");
            break;
          case "cloudy":
            console.log("Might rain later, stay prepared.");
            break;
          default:
            console.log("Unknown weather condition.");
        }
    
        // Ternary Operator for Even/Odd check
        let number = 10;
        let isEven = (number % 2 === 0) ? "Even number" : "Odd number";
        console.log(isEven);  // Outputs: "Even number"
      </script>
    </body>
    </html>
  2. Run the file in a browser:

    • Open the HTML file in a browser and open the Developer Tools (F12 or right-click and select Inspect > Console) to view the output of the script.

  3. Activity:

    • Step 1: Change the value of age and test how the ternary operator responds with different inputs.

    • Step 2: Modify the weather variable and test the switch statement by setting it to different values (e.g., "rainy", "cloudy").

    • Step 3: Add more case blocks to the switch statement for other types of weather, such as "snowy" or "windy".

    Challenge:

    • Ternary Operator Challenge: Write a ternary operation to check if a person is eligible to receive a senior discount (based on age being 65 or older).

      let age = 70;
      let seniorDiscount = age >= 65 ? "Eligible for senior discount" : "Not eligible for senior discount";
      console.log(seniorDiscount);
    • Switch Statement Challenge: Write a switch statement that outputs a message based on the current month (use numeric values for months, e.g., 1 for January, 2 for February, etc.).

    Example:

    let month = 12;
    switch (month) {
      case 1:
        console.log("January");
        break;
      case 2:
        console.log("February");
        break;
      case 12:
        console.log("December");
        break;
      default:
        console.log("Unknown month.");
    }

Follow-up Questions:

  1. How does the ternary operator help simplify basic if-else conditions? Can it always replace if-else?

  2. Why would you use a switch statement instead of multiple if-else-if conditions?

  3. When might a switch statement be less useful than if-else?

Expected Outcome:

Students will learn how to simplify if-else conditions using the ternary operator and how to handle multiple conditions in a more readable way using the switch statement. They will also understand when to use each approach in different scenarios.

Last updated