comparison operator WTF!

by Richard Hunter

HTML

<h1>String comparison WTF!</h1>
<p>
Triple equals compares by identity. This means that the two operands must refer to the SAME object in order for the expression to return true.
</p>
<p>
Double equals actually just delegates to triple equals for the comparison, but first it does a check for type. If the two operands are of the same type, they are compared using triple equals. If they are different types then Javascript attempts to convert them both to the same type. 
</p>
<p>
In the example here bar1 and bar2 are of different types (primitive string and string object) so Javascript converts them both to be a string literal and so a comparison with triple equals on these will return true.
</p>
<p>
When foo and foo2 are compared using double equals, because they are different instances of the same type, double (and hence triple equals) returns false.
</p>
<p>
This experiment seems to suggest that the string literal and the string object are different types. 
I need to investigate further into this issue. My understanding is that a string literal is still an object. This being so it appears that any one string is a singleton. Again, I am not certain about this.
</p>

JavaScript

/*
    String comparisons
*/
var foo = new String("foo");
var foo2 = new String("foo");

//  what will this output?
console.log("foo", foo == foo2);

var bar1 = "bar";
var bar2 = new String("bar");

// what will this output?
console.log("bar", bar1 == bar2);

//  Can you explain what is going on?