spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / experts / javascript / column26


The Modified Equality Operators

Developer News
News Flash: Adobe Has iPhone Workaround
Adobe's Flash 10.1 Goes Mobile (Minus iPhone)
A Salute to Visionary CEOs

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

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

webref The latest from WebReference.com Browse >
Building a Banking Application Home Page with OOP · Mixing Scripting Languages · Review: phpFox, a Social Networking CMS with all the Bells and Whistles
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Enterprise 2.0: Social Networking in the Cloud · BroadSoft Marketplace Hastens Pace of Telephony Innovation · Review: HTC Hero for Sprint


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

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