Skip to main content

The Switch Statement

Consider the following code.

 
if (button=="next") window.location="next.html";
else if (button=="previous") window.location="prev.html";
else if (button=="home") window.location="home.html";
else 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 enables 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.");
}
 

Next: Switch Components