JavaScript 1.3 Overview, Part II: The Modified Equality Operators - Doc JavaScript | WebReference

JavaScript 1.3 Overview, Part II: The Modified Equality Operators - Doc JavaScript


The Modified Equality Operators

JavaScript 1.3 changes the way equality operators work, reverting back to JavaScript 1.1's rules. JavaScript 1.2 handles standard equality operators the same way JavaScript 1.3 handles strict equality operators (see previous page). When the operators are of different types, JavaScript 1.2 does not attempt to do any type conversion to help the comparison -- it always returns false when the operands are of different types. The examples from previous page are relevant here as well. For example, the following standard equality test:

if (5 == "5")

returns false in JavaScript 1.2, because 5 is a number and "5" is a string.

Since JavaScript 1.3 explicitly supports strict equality operators (=== and !==), it can be more relaxed in the standard equality operators and do a type conversion before comparison, if necessary. Conversion is applied on operands of the type String, Number, Boolean, or Object.

The most common different-type-operand comparison is between a number and a string. The string is converted to a number via an elaborate algorithm. First, it is converted to a mathematical value. Then it is rounded to the nearest Number type value, according to the Number type of the other operand. For example, JavaScript 1.3 will return true for the following test:

if (5.12 == "5.12e0")

When you compare a number and a Boolean, the Boolean operand is converted to 1 if it is true, and to 0 if it is false. The following test will yield true:

if (1 == true)
as well as this one:

if (0 == false)

When you compare an Object with a Number, JavaScript 1.3 converts the Object to a Number by the valueOf() method. When you compare an Object with a String, JavaScript 1.3 converts the Object to a String by the toString() method. Referring to our previous assembly line example, the following test will yield true:

if ("[object Object]" == volvoInterior)

http://www.internet.com


Created: September 28, 1998
Revised: September 28, 1998

URL: http://www.webreference.com/js/column26/equality.html