Selection in JavaScript
A program which repeated the same sequence of commands every time that it ran would be
very little use. Most realistic program must respond in some way to events from the
outside world and change their behaviour to suit.
Selecting between two alternatives with if.
Even a very simple program such as a
digital clock can't just execute the same statements over and over again. It can run for
the first 59 minutes by just adding one to the time and displaying the value but at
the end of the first minute it must somehow know how to move from 00:59 to 01:00. A
simplified English description of this might be:
If the minute count is less than 60
then add one to the minutes
If not
then reset minutes to zero and add one to hours.
The program has to decide between two different courses of action and JavaScript has an
if
structure to do this.
Selecting between multiple choices with switch.
A calendar has a similar but more complex decision to make. All that a clock needs to
know is that there are 60 seconds in an hour so a simple test can switch it between its
regular "add a minute" routine and its "change hour" routine. A calendar needs to know
that January has 31 days, February has either 28 or 29 days, March has 31 days, and so on
through the year. The JavaScript language does this with the
switch
command structure.
|