Java Reference
In-Depth Information
assigning the results of Comparisons
You can store the results of a comparison in a variable, as shown in the following example:
var age = prompt("Enter age:", "");
var isOverSixty = parseInt(age, 10) > 60;
document.write("Older than 60: " + isOverSixty);
Here you obtain the user's age using the prompt() function. This returns, as a string, whatever value
the user enters. You then convert that to a number using the parseInt() function you saw in the
previous chapter and use the greater‐than operator to see if it's greater than 60. The result (either
true or false ) of the comparison will be stored in the variable isOverSixty .
If the user enters 35 , the document.write() on the final line will write this to the page:
Older than 60: false
If the user enters 61 , this will be displayed:
Older than 60: true
the if statement
The if statement is one you'll find yourself using in almost every program that is more than a
couple of lines long. It works very much as it does in the English language. For example, you might
say in English, “If the room temperature is more than 80 degrees Fahrenheit, then I'll turn the air
conditioning on.” In JavaScript, this would translate into something like this:
if (roomTemperature > 80) {
roomTemperature = roomTemperature - 10;
}
How does this work? See Figure 3-2.
Test Condition
If Test Condition is true, then
execute all the code inside the
curly braces
if ( roomTemperature > 80 )
{
roomTemperature = roomTemperature - 10;
}
figure 3-2  
Notice that the test condition is placed in parentheses and follows the if keyword. Also, note that
there is no semicolon at the end of this line. The code to be executed if the condition is true is
placed in curly braces on the line after the condition, and each of these lines of code does end with a
semicolon.
 
Search WWH ::




Custom Search