JavaScript, like a number of languages, supports another decision-making structure called switch. This is a useful alternative in HTML5 and CSS3 programming when you have a number of discrete values you want to compare against a single variable. Take a look at this name program:
function checkName(){ //from switch.html var name = prompt("What is your name?"); switch(name){ case "Bill Gates": alert("Thanks for MS Bob!"); break; case "Steve Jobs": alert("The Newton is awesome!"); break; default: alert("do I know you?"); } // end } // end checkName
The switch code is similar to an if-elseif structure in its behavior, but it uses a different syntax:
Indicate a variable in the switch statement.
In the switch statement's parentheses, place a variable or other expression. The switch statement is followed by a code block encased in squiggly braces ({}).
Use the case statement to indicate a case.
The case statement is followed by a potential value of the variable, followed by a colon. It's up to the programmer to ensure the value type matches the variable type.
End each case with the break statement.
End each case with the break statement. This indicates that you're done thinking about cases, and it's time to pop out of this data structure. If you don't explicitly include the break statement, you'll get strange behavior (all the subsequent cases will evaluate true as well).
Define a default case to catch other behavior.
Just like you normally add a default else to an if-elseif structure to catch any unanticipated values, the default keyword traps for any values of the variable that were not explicitly caught.
Useful as the switch structure seems to be, it can also be difficult, for the following reasons:
There are better options: The switch behavior can be built with the if-else structure, and can often be improved by using arrays or functions.
Switches are not good with inequalities: The switch structure works fine when there are discrete values to compare (like names) but are much more awkward when you're comparing a range of values (like temperatures).
The syntax is anachronistic: The syntax of the switch statement harkens back to the C language, developed in the early days of programming. The colons and break statements combine awkwardly with the braces used elsewhere to contain code fragments.
Use of the break keyword is discouraged: Normally the break keyword indicates you want to break the normal flow of your program. This is often used as a shortcut by sloppy programmers who can't come up with a more elegant way to write code. Because use of the break keyword is discouraged elsewhere in programming, it's weird to have a structure that requires its use.
Modern languages don't even have it: A number of the newer languages (like Python) don't support switch at all, so at some point you're likely to be in a language that cannot do switch. You might as well learn alternatives now.