spacer
Yehuda Shiran December 5, 1999
Identity Operators
Tips: December 1999

Yehuda Shiran, Ph.D.
Doc JavaScript

Developer News
Microsoft Shows Off Silverlight 4, IE9 Plans
Metasploit Expands Vulnerability Test Framework
HyperCard Reborn?

JavaScript's standard equality operators (== and !=) check if two expressions are equal (or not equal). If the two operands are not of the same type, JavaScript attempts to convert the operands to an appropriate type for the comparison. Values are considered equal if they are identical strings, numerically equivalent numbers, the same object, identical Boolean values, or (if different types) they can be coerced into one of these situations. Here are a few more rules:
  • NaN is not equal to anything including itself.
  • Negative zero equals positive zero.
  • null equals both null and undefined.

Every other comparison is considered unequal. JavaScript's identity (strict equality) operators (=== and !==) behave identically to the equality operators except no type conversion is done, and the types must be the same to be considered equal. Here are a few examples:

"3" == 3 // true
"3" === 3 // false
1 == true // true
1 === true // false
"1" == true // true
"1" === true // false

The problem with JavaScript's identity operators is that they are only supported by some browsers:

Browser:IE4IE5N2N3N4/C4 (JS1.2)N4.06/C4.5 (JS1.3)
Type Conversion (== and !=)yesyesyesyesnoyes
Available (=== and !==)yesyesnononoyes

IE = Microsoft Internet Explorer
N = Netscape Navigator (standalone)
C = Netscape Communicator

We can use the typeof operator to achieve the same results:

function seq(x, y) { // ===
  return ((typeof(x) == typeof(y)) && (x == y)); // AND
}

function sneq(x, y) { // ===
  return ((typeof(x) != typeof(y)) || (x != y)); // OR
}

seq("3", 3) // false
sneq("3", 3) // true
seq(1, true) // false
sneq(1, true) // true
seq("1", true) // false
sneq("1", true) // true
seq(5, 5) // true
sneq(5, 5) // false


People who read this tip also read these tips:

Look for similar tips by subject:

internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

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

webref The latest from WebReference.com Browse >
Rolling Out Your Own HTML Application Version Control · HTML 5: Client-side Storage · Working with Ajax Server Extensions
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
Wi-Fi Product Watch, November 2009 · Chip Market Recovering From '08 Collapse · Low-Cost Tools to Kickstart Your New Business