spacer

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

home / experts / javascript / column26


The Modified Equality Operators

Developer News
ActiveState Debuts Open Source Business Suite
Salesforce Offers Visual App Builder
Codesion Steps Out From CVS's Shadow

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


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Use Web Caching to Make Your Web Site Faster · Creating an Online Shopping Cart Mechanism in PHP · Log JavaScript Errors Using an AJAX-driven Web Service
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Configuring Granular Settings for a Database Level Audit · The Perils of a Web 2.0 Transition on Your Business Processes · Facebook Redesigns Site —Again — Nears 400M Mark


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

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