Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

82 CHAPTER 3 Getting started with JavaScript


Using the switch keyword
The switch keyword can be used when a single value is to be examined and, based on
its value, there could be several outcomes. Consider the following example that uses the
switch keyword, in which the user is prompted to select a color for the car that he or she is
purchasing:
var carColor = prompt('What color car would you like to buy?', 'white');
switch (carColor) {
case 'red':
alert('Red is a fancy choice!');
break;
case 'black':
alert('Black looks nice, but you need to wash often!');
break;
case 'white':
alert('White is in stock and you get a discount!');
break;
default:
alert('The color:' + carColor + ' is not known.');
break;
};

In this example, the user is prompted to enter a car color and presented with a default
value of white. The switch keyword examines carColor to see whether its value matches any of
the values provided in the cases. If there is a match, the code within the case is executed until
the code reaches either a break or a return keyword. If there is no break or return, the code
continues into the next case or default.
How do you use the switch with numeric ranges? Many people would say that you can’t
work with numeric ranges because the switch is looking for an exact match to a case value,
but there is a trick to solving this problem. Consider the cascading if example, covered earlier,
when the program produced a different message based on the user’s age response. Four
different categories of responses—if the age was not a number, if it was greater than or equal
to 50, if it was less than or equal to 20, or if it was any other number—received four different
messages. The following is a rewrite of the cascading if as a switch:
var age = prompt('Enter your age', '');
age = Number(age);
switch (true) {
case isNaN(age):
age = 0;
alert('You need to enter a valid number');
break;
case (age >= 50):
age = Number(age) + 1;
alert("You're old! You will soon be " + age + " years old!");
break;
case (age <= 20):
age = Number(age) + 1;
Free download pdf