Page 99 - DCAP202_Fundamentals of Web Programming
P. 99
Fundamentals of Web Programming
Notes
Example: To illustrate further, we’ll use the nesting of if / else statements in a couple of
working examples, shown below.
if (99<100) {
document.write(“Expression1 has evaluated to true!!”);
} else {
if (80<100) {
document.write(“Expression2 has evaluated to true!!”);
} else {
document.write(“Expression2 has evaluated to false!!”);
}
}
The example shows the nesting of an if / else statement within another. The first if / else
statement shows the less than operator being used to evaluate the weights of two numbers,
99 and 100. Since 99 is indeed less than 100, the conditional expression returns a value of true, and
the first document.write statement (“Expression1 has evaluated to true!!”) is written to the
screen. The false section of the first if / else statement is never consulted, since the conditional
expression of the first if / else statement evaluated to true.
Examine the below example, which utilizes the decision making ability of the second, nested,
if / else statement.
if (101<100) {
document.write(“Expression1 has evaluated to true!!”);
} else {
if (80<100) {
document.write(“Expression2 has evaluated to true!!”);
} else {
document.write(“Expression2 has evaluated to false!!”);
}
}
Since 101 is less than 100, and the conditional expression of the first if / else statement returns
false, the second if / else statement is executed. Since 80 is less than 100, the conditional expression
returns a value of true and the first document.write statement of the second if / else statement is
executed, writing “Expression2 has evaluated to true!!” to the screen.
8.1.2 Switch Statement
The switch case conditional statement is used to test all of the possible outcomes for the application
you are designing. Used with the case keyword, the switch statement can give you the control
you require, with many actions possible instead of just the two given with an if / else statement.
That is, you are not limited to a true or false answer to decide between only two actions. While
the true or false decision is still used at a very basic level, you may have as many outcomes as
you have a need for.
Examine the syntax example, given below.
switch (expression)
{
case caseLabel:
statement;
break;
case caseLabel:
92 LOVELY PROFESSIONAL UNIVERSITY