while (x-- > 0) {
product += y;
}
product *= sign;
Professor: Good work.
8.2 switch Conditional
Professor: Today you are going to learn how to use objects, which will allow you to
build considerably more elaborate programs. But we’ll also cover two more control
statements of JavaScript. The first one is the switch conditional.
You already know th e if/else statement, which allows you to choose between two
alternatives. Sometimes, however, you have more than two alternatives to select from,
in which case it would be wasteful to repe atedly evaluate one and the same expres-
sion in multiple if/else statements. That’s whe re another control statement called
switch jumps in. Its syntax is as follows:
switch (expression ) {
case expression_1 : statements_1
case expression_2 : statements_2
...
case expression_n : statements_n
default: other_statements
}
It look s complicated at first glance but it’s really q uite simple. First, expression is
evaluated and compared to the expressions from expression_1 to expression_n ,
one after the other, using the strict eq uality operator (===). As soon as a comparison
evaluates to true, no more comparisons are made. Instead, the statements at the right
begin to execute, starting with the statement after the case keyword where a compari-
son first returned tr ue. For example, if expression equals to expression_2 , then
all the statements starting from statements_2 are executed.
Incidenta lly, yo u can use as many c ase statements as you like. However, if none of
the comparisons returns true, then other_statements are executed, which are put
after the default keyword . This is optional, though, and you don’t have to include
the default keyword.
Mike: I don’t understand this. It seems that other_statements are always exe-
cuted, regardless of the actual outcome of the comparisons. Am I missing something?
Professor: Very good observation, indeed. The switch statemen t is usually aug-
mented with break statements to reach its full functionality, but more about that later.
As an example, consider a p roblem w here you have to append an appropria te suffix to
a number in order to produce an ordinal number. In the English language, there are
four different suffixes: “st,” “ nd,” “rd,” and “th.” From what we have learned about
the switch statement we can produce th e following code:
150 Meeting 8. Introducing Objects