Welcome to Bucaro TecHelp!

Bucaro TecHelp
Maintain Your Computer and Use it More Effectively
to Design a Web Site and Make Money on the Web

About Bucaro TecHelp About BTH User Agreement User Agreement Privacy Policy Privacy Site Map Site Map Contact Bucaro TecHelp Contact RSS News Feeds News Feeds

Java Script Comparison Operators

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");
  alert("The strings are NOT equal");

if(strFirst.toLowerCase() == strSecond.toLowerCase())
  alert("The strings are equal");
  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");
  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.

RSS Feed RSS Feed

Follow Stephen Bucaro Follow @Stephen Bucaro

Fire HD
[Site User Agreement] [Privacy Policy] [Site map] [Search This Site] [Contact Form]
Copyright©2001-2018 Bucaro TecHelp 13771 N Fountain Hills Blvd Suite 114-248 Fountain Hills, AZ 85268