HTML and CSS Reference
In-Depth Information
Figure 12-22
nested if statement for leap years
if the year is divisible by
4 and either n ot divisible
by 100 or divisible by
400, it's a leap year
3. Save your changes to the file.
Exploring the if else Statement
The if statement runs a command or a command block only if the conditional expres-
sion returns the value true ; it does nothing if a value of false is returned. On some
occasions, you might want to choose between alternate command blocks. In those cases,
you will use an if else structure in which one command block is run if the conditional
expression is true, and a different command block is run if the expression is false. The
general structure of an if else statement is as follows:
if ( condition ) {
commands if condition is true
} else {
commands if otherwise
}
If only a single command is run in response to the if statement, you can use the follow-
ing abbreviated form:
if ( condition ) command if condition is true
else command if otherwise ;
The following example shows an if else statement that runs one of two possible
document.write() commands depending on whether the value of the day variable is
Friday or not:
if (day == “Friday”) document.write(“Thank goodness it's Friday”)
else document.write(“Today is “ + day);
In this statement, the text Thank goodness it's Friday is written to the document if the
value of the day variable is Friday . Otherwise, the statement writes the name of the day.
 
Search WWH ::




Custom Search