Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 7 - The Switch Statement

We saw conditional statements in lesson 5. We a bit of practice, you might have realized that the if-else statement can become very combersom if the conditions become many. If you try an excercise of finding the largest number among three numbers A, B, and C using if-else statements, you will quickly notice how deep and messy it becomes. You can read more about that here.

To solve this problem, I introduce in this lesson, another tool that can help in writing cleaner, simpler, and faster code in such situations: The Switch statement

let day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the workweek!");
    break;
  case "Wednesday":
    console.log("Midweek already.");
    break;
  case "Friday":
    console.log("Weekend is near!");
    break;
  default:
    console.log("Just another day.");
}

Explanation:

  • The switch statement is used when you have multiple possible values for a variable.

  • case checks if the value matches and executes the associated code.

  • break prevents execution from falling through to the next case.

  • The default case runs if no case matches.

Try your hand:

  1. Create a File:

    • Create a new file named day7-switch-statement.html.
  2. Write the Code:

    • Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Day 7 - Switch Statement</title>
</head>
<body>
    <script>
        let day = "Monday";

        switch (day) {
            case "Monday":
                console.log("Start of the workweek!");
                break;
            case "Wednesday":
                console.log("Midweek already.");
                break;
            case "Friday":
                console.log("Weekend is near!");
                break;
            default:
                console.log("Just another day.");
        }
    </script>
</body>
</html>

Save the file in your folder.

  1. Preview the File:

    • Open the file in your browser and access the developer console.
    Start of the workweek!
  2. Experiment:

    • Change day to "Wednesday", "Friday", or any other day.

    • Save the file and refresh the browser to see different outputs.