Friday, September 12, 2008

Javascript: Equality versus Identity

Javascript has 2 basic forms of comparison operators: === and == .== is the standard equality operator while === is the identity operator. The equality operator will perform casting and usually test both sides as strings. The identity operator compares the value each side the type, but it does not work like instanceof.

Recently we did some experiments with the different return values.

The Expressions

ExpressionResult
"test" == "test"
true
"test" === "test"
true
String("test") === "test"
true
new String("test") == "test"
true
new String("test") === "test"false
new String("test") === new String("test")
Before Firefox 3.0.1: true
After: false
new String("test") === String("test")
false

Here are some type tests we performed
ExpressionType
typeof("test")
"string"
typeof(String("test"))
"string"
typeof(new String("test"))
"object"
typeof(function(){})
"function"


What Did we Learn?
First we see that a string is not always a string. Sometimes it's an object. It's easy to forget that Javascript still has the concept of primitives and objects. Integers, Strings and a few others are all primitives. When using the identity operator (===) you have to assume that it is comparing the value of the variable and it's type (as returned by typeof). Further compounding this is the fact that new String() does not type to a "STRING", while calling String as a function does.

What this all suggests is that when dealing with primatives you might as well use the equality operator (==). If you feel it's safer to use the identity operator (===) then you should use String() as a function and never use new String().

3 comments:

Anonymous said...

I recently ran into related issues, and I'd like to point out -- in Firefox 3.0.1 at least -- that new String("zulu") === new String("zulu") evaluates to false, not true. This is what the specification requires. Identity with two objects requires that they be the exact same object.

On the other hand "zulu" === "zulu" returns true.

I'm still searching for a reason why '===' doesn't work when the two objects are both String instances that JavaScript knows about.

I could see '===' failing if the two objects were ZooBar instances that JavaScript knew nothing about.

I suppose they might have done it just to make '===' work the same for all objects, but it still bugs me.

buy dissertation online said...

I'm a B.Tech graduation student. I'm learning java script. This tutorial helps me to learn some new things. Thank you for having this great blog.

for IT the said...

JavaScript Online Training JavaScript Online Training JQuery Online Training JQuery Online Training
JavaScript Course | HTML5 Online Training