Spelchan.com Logo

From Scratch Web Games: A Beginners Guide to Game Development using HTML, CSS, and JavaScript

Chapter 4.12: The Switch Statement

The Switch statement is a convenient way of handling situations where you need to handle many actions based on the value of a variable. The Switch statement starts of with the switch keyword which contains an expression that represents the value you wish to match as if you were using the === operator. This, as a reminder, is an equal where both sides of the expression must be the same type. After the switch statement is a block of code which consists of case statements and an optional default statement. Here is a simple example:

switch (number)
   case 1:
      console.log("The number is one");
   case 2:
      console.log("The number is two");
   case 3:
      console.log("The number is three");
      console.log("The number is not one, two or three");

After each of the case statements is the code you want to execute if the variable being switched equals the value of the case. The code should end with a break statement, which causes the program to skip over the rest of the switch block. If there is no break statement, then all code in the following case statement will also be executed, which we call fall through. In some cases, this is exactly what you want to happen, as it allows you to define a group of numbers that all do the same action. Forgetting the break statement is a very common mistake for beginners to make and is even something that experts have made resulting in devastating results.

The default statement will be executed if none of the case statements match the value of the switch expression. No break statement is needed after the default code, though I usually do have a break statement out of habit. While the default statement is optional, it is a good habit to always have a default action, even if the default is simply a trace statement telling you that you have reached code that should not be reached.

The switch statement we have above could be done with if statements as you can see below.

if (number == 1) {
   console.log("The number is one");
} else if (number == 2) {
   console.log("The number is two");
} else if (number == 3) {
   console.log("The number is three");
} else {
   console.log("The number is not one, two or three");

The choice between using switch and if statements is more of a cosmetic one with JavaScript. Switch statements are a convenience statement designed to replace large numbers of if then else statements in a more readable way.

The switch statement comes directly from the C programming language. While I am a fan of that language, being one of the first programming languages that I learned, I have been bitten by the switch statement too many times and have uncovered bugs in other people’s code due to the forgetting of a break statement frequently. Therefore, I am happy that new languages are replacing the default fall-through behavior with default break behavior requiring a statement to fall through.

Another common bug with the switch statement is not having a default block when a case does not cover all possibilities. The result of not having a default is essentially a default that does nothing which may be what you want. It could also be an indication that you expect only the values in the case to exist. Having a default that reports an error if it is reached is recommended in this situation.

The switch statement can be used with any data type as long as the strict equality will distinguish the correct results. Generally it tends to be used with numbers or strings. For a more complicated example, here is the rock-scissors-paper game from the last section rewritten to use the switch statement:

let s = p1Choice + " vs " + p2Choice;
if (p1Choice === p2Choice) {
   s += " is a draw"
} else {
   switch (p1Choice) {
      case "Rock":
         if (p2Choice === "Scissors")
            s += " Rock smashes Scissors so Player one wins!";
            s += " Paper covers Rock so Player two wins!";
      case "Scissors":
         if (p2Choice === "Paper")
            s += " Scissors cuts Paper so Player one wins!";
            s += " Rock smashes Scissors so Player two wins!";
      case "Paper":
         if (p2Choice === "Rock")
            s += " Paper covers Rock so Player one wins!";
            s += " Scissors cuts Paper so Player two wins!";
         s = "Unknown choice.";

Next we are going to look at functions, a way of repeating code without having to re-type it.

Chapter contents

Chapter 4 Contents

4.1 Cheat Sheets

A quick summary of the basics of JavaScript.

4.2 History of JavaScript

A brief look at how JavaScript was written in 10 days.

4.3 Comment Controversy

Comments. Why programmers don't write them, and how they should be written

4.4 Variables

Variables are used to store the state of a program.

4.5 (extra) How Computers Represent Data

Bits, Bytes, and data types.

4.6 Math

Math on the computer similar but some symbol differences.

Math functions

Various math operations can be used through the Math class.

4.8 Strings

Strings are what we call blocks of text and are used extensively.

4.9 Calculating true and false

Determining if a conditional expression is true or false

4.10 if (Conditional statements)

Conditional code using the if statement.

4.11 Nested conditions

If statements can contain other if statements, this is called nesting.

4.12 Switch statement

Switch statements are a way of replacing large number of else if statements.

4.13 Functions

Functions let you put common code into a named function that can be called anywhere.

4.14 Looping

Loops allow you to repeat sections of code until conditions are met.

4.15 Nested loops

Just like conditional statements, loops can be nested but this has some special considerations.

4.16 Accessing the Web page

Scripting languages give us the ability to dynamically change the web page.

4.17 Events

Reacting to the user actions is done by handling events.

4.18 Project: Where’s Wendy

Coming June 23rd, 2024

4.19 Project: Where’s Wendy implementation

Coming June 30th, 2024

← previous section
Nested Conditions
next section →
Table of Contents