Sams Teach Yourself JavaScript in 24 Hours

Sams Teach Yourself JavaScript in 24 Hours

By Michael Moncur

Using Multiple Conditions with switch

Often, you'll use several if statements in a row to test for different conditions. Here is one example of this technique:

if (button=="next") window.location="next.html";
if (button=="previous") window.location="prev.html";
if (button=="home") window.location="home.html";
if (button=="back") window.location="menu.html";

Although this is a compact way of doing things, this method can get messy if each if statement has its own block of code with several statements. As an alternative, JavaScript includes the switch statement, which allows you to combine several tests of the same variable or expression into a single block of statements. The following shows the same example converted to use switch.

switch(button) {
    case "next":
        window.location="next.html";
        break;
    case "previous":
        window.location="prev.html";
        break;
case "home":
        window.location="home.html";
        break;
case "back":
        window.location="menu.html";
        break;
default:
        window.alert("Wrong button.");
}

The switch statement has several components:

Share ThisShare This

Informit Network