When checking a variable to see if it is one thing or another IF is ideal. If it can be three things you can add an ELSEIF which is really just shorthand for nexted IFs. Beyond that things can get complicated so using SWITCH becomes useful. This one might be used when a user selects which recipes to show on a page:
var chosenMeat='vegetarian';
switch (chosenMeat) {
case 'chicken':
alert('Poultry preferred');
break;
case 'beef':
alert('Cow chosen');
break;
case 'vegetarian':
alert('Against animal');
break;
default:
alert('Glutton');
}
The variable in the brackets (chosenMeat) is set outside of the SWITCH statement (probably coming from a form or user event in a real page). Then the SWITCH statement looks at what is in chosenMeat. Each of the choices is looked at in turn. If the value in the variable matches a CASE then the code is executed. There is no real code here to keep the example simple.
The CASEs and all of the code for them are held inside curly brackets (braces).
The BREAK is there because when a CASE is matched there is no point in checking the rest of the CASEs for a match. BREAK jumps out of the whole SWITCH statement. If none of the CASEs match then the DEFAULT code is used. You may not always need a default. You might also sometimes not need the BREAKs as it might be possible to have more than one match with cumulative actions.




