Java Reference
In-Depth Information
When you load it into your browser, a prompt box should appear. Enter the value 30, then press Return,
and the lines shown in Figure 3-6 are written to the web page.
myAge is NOT between 0 and 10
myAge is between 30 and 39 or myAge is between 80 and 89
Figure 3-6
The script block starts by defi ning the variable myAge and initializing it to the value entered by the user
in the prompt box and converted to a number.
var myAge = Number(prompt(“Enter your age”,30));
After this are four if statements, each using multiple conditions. You'll look at each in detail in turn.
The easiest way to work out what multiple conditions are doing is to split them up into smaller pieces
and then evaluate the combined result. In this example you have entered the value 30 , which has been
stored in the variable myAge . You'll substitute this value into the conditions to see how they work.
Here's the fi rst if statement:
if (myAge >= 0 && myAge <= 10)
{
document.write(“myAge is between 0 and 10<br />”);
}
The fi rst if statement is asking the question “Is myAge between 0 and 10?” You'll take the LHS of the
condition fi rst, substituting your particular value for myAge . The LHS asks “Is 30 greater than or equal
to 0?” The answer is true . The question posed by the RHS condition is “Is 30 less than or equal to 10?”
The answer is false . These two halves of the condition are joined using && , which indicates the AND
operator. Using the AND results table shown earlier, you can see that if LHS is true and RHS is false ,
you have an overall result of false . So the end result of the condition for the if statement is false ,
and the code inside the braces won't execute.
Let's move on to the second if statement.
if ( !(myAge >= 0 && myAge <= 10) )
{
document.write(“myAge is NOT between 0 and 10<br />”);
}
The second if statement is posing the question “Is myAge not between 0 and 10?” Its condition is similar
to that of the fi rst if statement, but with one small difference: You have enclosed the condition inside
parentheses and put the NOT operator ( ! ) in front.
The part of the condition inside the parentheses is evaluated and, as before, produces the same result —
false. However, the NOT operator reverses the result and makes it true. Because the if statement's
condition is true, the code inside the braces will execute this time, causing a document.write() to write
a response to the page.
What about the third if statement?
if ( myAge >= 80 || myAge <= 10 )
{
document.write(“myAge is either 80 and above OR 10 or below<br />”);
}
Search WWH ::




Custom Search