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().