Java Reference
In-Depth Information
You could also include another if statement with the else statement. For example
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10”);
}
else if ( (myAge >= 30 && myAge <= 39) || (myAge >= 80 && myAge <= 89) )
{
document.write(“myAge is between 30 and 39 “ +
“or myAge is between 80 and 89”);
}
else
{
document.write(“myAge is NOT between 0 and 10, “ +
“nor is it between 30 and 39, nor is it between 80 and 89”);
}
The fi rst if statement checks whether myAge is between 0 and 10 and executes some code if that's
true. If it's false, an else if statement checks if myAge is between 30 and 39 or 80 and 89, and
executes some other code if either of those conditions is true. Failing that, you have a fi nal else state-
ment, which catches the situation in which the value of myAge did not trigger true in any of the earlier
if conditions.
When using if and else if, you need to be extra careful with your curly braces to ensure that the
if and else if statements start and stop where you expect, and you don't end up with an else that
doesn't belong to the right if. This is quite tricky to describe with words — it's easier to see what we
mean with an example.
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10”);
if (myAge == 5)
{
document.write(“You're 5 years old”);
}
else
{
document.write(“myAge is NOT between 0 and 10”);
}
Notice that we haven't indented the code. Although this does not matter to JavaScript, it does make the
code more diffi cult for humans to read and hides the missing curly brace that should be before the fi nal
else statement.
Correctly formatted and with the missing bracket inserted, the code looks like this:
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10<br />”);
if (myAge == 5)
{
document.write(“You're 5 years old”);
}
Search WWH ::




Custom Search