Javascript Switch Statements

Sometimes, you'll have more than one value to check for your variables. You can do the checking with a lot of if ... else statements. Or you can use something called a switch statement. Here's an example:

var age = 17;

switch (age) {

case 17:

document.write("under 18");

break;

case 24:

document.write("over 18");

break;

default:

document.write("can't tell");

break;

}

In this example, we've set up a variable called age. We've then stored a value of 17 in the age variable. The switch statement examines what this value is. If it's the case that age hold a value of 17 then its code gets executed. The break keyword is for escaping the switch statement. If you miss it out Javascript will continue downwards and assume all your other cases are true, thus executing the rest of the case code. If none of your cases apply, a default value can be added.

But note the syntax for the switch statement. The word switch is lowercase. After this, you have a pair of round brackets. Inside the round brackets you type a variable name or add a condition to test. This will be evaluated to either true or false, depending on which case matches. Javascript will look at your list of cases and try to find a match. If it finds one, it executes that code. If it doesn't find one then the default option is executed. Note where all the curly brackets and colons are. You have a pair of curly brackets for the entire switch statement. You have a colon after each case.

However, switch statements in Javascript are not very useful as they don't allow you to test a range of values very easily, or at all. If you were checking for age ranges you want to check things like 18 to 30, 31 to 50, etc. Javascript switch statements don't allow you to do this, so you'd have to have one case for each age - a lot of cases, in other words. They can be useful in limited situations, though, so they're worth knowing about.