HTML and CSS Reference
In-Depth Information
EXAMPLE
5.7
<html>
<head>
<title>Comparing Strings</title>
</head>
<body>
1
<script type="text/javascript">
2
var fruit1 = "pear";
var fruit2 = "peaR";
3
var result = fruit1 > fruit2;
4
document.write( "<h3>The result is "+
result
+ ".<br />");
5
result = fruit1 < fruit2;
6
document.write( "The result is " + result + ".<br />");
7
result = fruit1 === fruit2;
//
Are they identical; i.e., value and type are the same?
8
document.write( "The result is " + result + ".<br />");
</script>
</body>
</html>
EXPLANATION
1
This is the start of the JavaScript program.
2
The variables,
fruit1
and
fruit2
, are assigned to string values, differing by only one
letter.
3
The string values are compared and a Boolean value of
true
or
false
will be re-
turned and assigned to the variable,
result
.
“pear”
is greater than
“peaR”
because
the
r
has an ASCII value of 114 and the
R
has an ASCII value of 82.
4
The result of the comparison in line 3 is
true
and the result is sent to the browser.
5
This time
“pear”
is compared to
“peaR”
with the less than operator. The result is
false
.
6
The result of the comparison in line 5 is
false
and the result is sent to the browser.
7
The identical equality operator is used. Because the strings are not identical, the
result is
false
.
8
The result of the comparison in line 7 is
false
and the result is sent to the browser.
The output of the script is shown in Figure 5.10.
Figure 5.10
Output from Example 5.7: String comparison.