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) > 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 pre-
vious 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 fi nal line will write this to the page:
Older than 60: false
If the user entered 61, this will be displayed:
Older than 60: true
The if Statement
The if statement is one you'll fi nd 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 )
{
roomT emperature = 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