Comparisons
o Comparison operators compare two values with each other. Most commonly, they are used to compare the contents of two variables – for example we might want to check if the value of var_1 was numerically greater than that of var_2.
o When you use a comparison operator, the value that is returned from the comparison is invariably a Boolean value of either true or false. For example, consider the following statements:
var_1 = 4; var_2 = 10;
var_3 = var_1 > var_2;
In this case, the value of var_3 is false. Note that the Boolean value of false is not the same as the text string “false”:
var_4 = false; // Boolean value var_5 = “false”; // Text string o Common comparison operators are given below:
Comparison | Function |
x == y | Returns true if x and y are equivalent, false otherwise |
x != y | Returns true if x and y are not equivalent, false otherwise |
x > y | Returns true if x is numerically greater than y, false otherwise |
x >= y | Returns true if x is numerically greater than or equal to y, false otherwise |
x < y | Returns true if y is numerically greater than x, false otherwise |
x <= y | Returns true if y is numerically greater than or equal to x, false otherwise |
o To reverse the value returned from a comparison, we generally modify the comparison operator with a ! (a “bang”). Note that in many cases this is not necessary, but can aid comprehension:
var_1 !> var_2; var_1 <= var_2;
both of these are equivalent, but one may make more semantic sense in a given context than the other.
Project
o Open your previous project file, and save it under the name chapter_12.html.
o Ensure that your two variables both have numerical values in them and not strings.
o Use an alert box to display the result of a comparison of your two variables for each of the comparison operators listed above.
o Substitute one of the numerical values for a text string and repeat the procedure. Note the differences.
Recent Comments