Java Script Comparison Operators
By Stephen Bucaro
A comparison operator compares two values and returns the result "true" or "false". Below is a list of comparison operators.
Operator |
Tests For |
== | two values are equal |
!= | two values are not equal |
> | first value is greater than second value |
>= | first value is equal to or greater than second value |
< | first value is less than second value |
<= | first value is equal to or less than second value |
For comparing numeric values the operators perform the same as they do in algebra.
For comparing character strings, each character in the strings is converted to its
ASCII value and then a numeric comparison is made of the ASCII values all the characters
of the two character strings.
The ASCII values of upper case characters are not the same as their lower case
values. When you want to compare two character strings disregarding case, use the
string objects .toUpperCase or .toLowerCase methods to set the characters of the
two strings to the same case.
var strFirst = "My Character String";
var strSecond = "my character string";
if(strFirst == strSecond)
alert("The strings are equal");
else
alert("The strings are NOT equal");
if(strFirst.toLowerCase() == strSecond.toLowerCase())
alert("The strings are equal");
else
alert("The strings are NOT equal");
A common test used in form validation is to compare the contents of a text box
with an empty string, as shown below.
if(form.inputbox.value != "")
alert("Enter input value");
Comparing Different Data Types
If you compare a numeric value to a string value, Java Script automatically converts
the string to a number before performing the comparison.
var numValue = 123;
var strValue = "123";
if(numValue == strValue)
alert("The numbers are equal");
else
alert("The numbers are NOT equal");
You may want to compare other dissimilar data types such as a date to a number,
or you may just not want to accept the ambiguity of Java Script's internal data type
conversions. In that case you could do an explicit data type conversion before
performing the comparison.
|