Comparison Operators
By Stephen Bucaro
Comparison operators compare the values of two variables or statements and
return the result of the comparison as either true or false.
operator | comparison |
> | greater than |
< | less than |
== | equal to |
!= | not equal to |
<= | less than or equal to |
>= | greater than or equal to |
The result of the comparison can be used to control the flow of the program. The
if/else structure is the most commonly used control structure.
var nPrice = 29.00;
var nHighest = 32.00;
if(nPrice < nHighest)
{
document.write("buy it!");
}
else
{
document.write("don\'t buy it.");
}
The code shown above would print "buy it." because the value of nPrice is lower
than the value of nHighest. The comparison operator (<) returns true,
and the code inside the if block is executed.
If the value of nPrice was higher than the value of nHighest, the result
of the comparison would be false and the program flow would drop down to the else
statement. The program would print "don't buy it."
The if structure is frequently used without the else block as shown below.
In this case, if the value of nPrice was higher than the value of nHighest,
the result of the comparison would be false and the program flow would drop through,
not printing anything.
var nPrice = 29.00;
var nHighest = 32.00;
if(nPrice < nHighest)
{
document.write("buy it!");
}
Another control structure is the do/while loop as shown below.
var nPrice = 64.00;
var nHighest = 32.00;
do
{
--nPrice;
} while (nPrice > nHighest);
This structure loops through the code inside the curly brackets, which decrements the
value of nPrice on each loop. Then it performs the comparison in side the brackets
following the while statement to see if the value of nPrice is greater than
the value of nHighest. If the result of the comparison is true, the program
executes the statement inside the brackets, decrementing the value of nPrice again.
This continues until the result of the comparison is false. Then the program flow
breaks out of the loop.
Comparison operators compare the values of two variables or statements and return the
result of the comparison as either true or false. The result of the comparison
can be used to control the flow of the program.
More Java Script Code: • Search and Replace Strings • Java Script Math.tan Method • Determine Minimum and Maximum • Use moveBy Method to Move Window by a Specific Offset • The break Statement • Extract Part of a String • Convert a Number to a String • Cookie Power Made Easy • Generating Random Numbers • Accessing Web Page Elements
|