HTML and CSS Reference
In-Depth Information
EXAMPLE
6.3
<html>
<head>
<title>Conditional Flow Control</title>
</head>
<body>
<h2>
1
<script type="text/javascript">
<!--
2
var age=eval( prompt("How old are you? ",""));
3
if( age > 0 && age <= 12 ){
4
alert("You pay the child's fare. ");
}
5
else if( age > 12 && age < 60 ){
6
alert("You pay the regular adult fare. ");
}
else {
7
alert("You pay the senior fare! ");
}
//-->
8
</script>
</h3>
</body>
</html>
EXPLANATION
1
JavaScript program starts here.
2
The prompt dialog box will display the message “
How old are you?
”. Whatever the
user types into the box will be converted to a number by the
eval()
method and
then stored in the variable
age
.
3, 4
If the value of the variable
age
is greater than
0
and
age
is also less than or equal
to
12
, then line 4 is executed and the program continues at line 8.
5, 6
If the expression on line 3 is false, the JavaScript interpreter will test this line, and if
the age is greater than 12 and also less than 60, the block of statements that follow
will be executed and control goes to line 8. You can have as many
else if
s as you like.
7
The
else
statement, line number 7, is executed if all of the previous expressions
test false. This statement is called the default and is not required.
8
This tag marks the end of the JavaScript program.
The
switch
statement is an alternative to
if/else if
conditional construct (commonly
called a “case statement”) and may make the program more readable when handling
multiple options.